问题描述
假设我有一个连接到 mongoDB 的 node.js 服务器.然后 mongoDB 死掉或断开连接.当然,node.js 服务器会失去连接.即使我重新启动 mongoDB,node.js 服务器也不会自动连接到新的 mongodb,即使它运行在具有相同端口的同一台机器上.我需要重新启动 Node.js 服务器或以某种方式编写自己的例程来重新连接它.
Let say I have a node.js server connecting to a mongoDB. Then the mongoDB die or disconnect. Of course, node.js server will lose connection. Even if I restart mongoDB, node.js server will not connect to the new mongodb automatically even it is running on the same machine with same port. I need to either restart Node.js server or somehow write my own routine to reconnect it.
是否有任何节点模块来处理重新连接?并且以一种不那么激进的方式.(即不会每秒都要求连接).
Is there any node module to handle reconnection? and in a less aggressive way. (i.e. won't ask for connection every second).
推荐答案
这个问题的答案取决于你的驱动版本和你的具体代码.
The answer to this question will depend on your driver version and your specific code.
最新的驱动程序版本应该支持连接池.这通常意味着您在尝试第一次连接时可能会遇到异常,但您应该能够重新连接.
The most recent driver versions should support connection pooling. This typically means that you may get an exception when attempting a first connection, but you should be able to re-connect.
您的实施也很重要.有几种方法可以做到这一点.有些人会在启动 Web 服务器之外打开连接,有些人会响应请求.
Your implementation is also important. There are several ways to do this. Some people open a connection outside of starting the web server, others do it in response to requests.
如果您有连接池,那么您应该能够在每个请求上打开连接".您必须在重启后正确处理错误,但您不需要重启 Node 环境.
If you have connection pooling, then you should be able to "open a connection" on every request. You will have to handle the errors correctly after reboot, but you should not need to restart the Node environment.
这篇关于如何在 node.js 服务器中自动重新连接 mongo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!