如何在node.js服务器中自动重新连接mongo? [英] How to reconnect mongo automatically in node.js server?

查看:346
本文介绍了如何在node.js服务器中自动重新连接mongo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个node.js服务器连接到一个mongoDB。然后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.

如果您有连接池,那么您应该能够打开连接。您必须在重新启动后正确处理错误,但不应重新启动节点环境。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆