如何在node.js服务器中自动重新连接mongo?
假设我有一个连接到 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题的答案将取决于您的驱动程序版本和特定代码。
最新的驱动程序版本应支持连接池。这通常意味着您在尝试第一次连接时可能会遇到异常,但您应该能够重新连接。
您的实施也很重要。有几种方法可以做到这一点。有些人在启动 Web 服务器之外打开连接,其他人则是为了响应请求而这样做。
如果您有连接池,那么您应该能够对每个请求“打开连接”。重新启动后,您必须正确处理错误,但不需要重新启动 Node 环境。
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.
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.
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.