可靠地重新连接到MongoDB [英] Reliably reconnect to MongoDB

查看:185
本文介绍了可靠地重新连接到MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:我在驱动程序上使用2.1版本,而不是3.2

UPDATE: I am using the 2.1 version on the driver, against 3.2

我有一个使用MongoDB的节点应用程序.我的问题是,如果MongoDB服务器由于任何原因而关闭,则应用程序不会重新连接. 为实现此目的,我基于此官方教程中的代码进行了测试.

I have a node application that uses MongoDB. The problem I have is that if the MongoDB server goes down for any reason, the application doesn't reconnect. To get this right, I based my tests on the code in this official tutorial.

var MongoClient = require('mongodb').MongoClient
  , f = require('util').format;

MongoClient.connect('mongodb://localhost:27017/test', 

// Optional: uncomment if necessary
// { db: { bufferMaxEntries: 3 } },


function(err, db) {
  var col = db.collection('t');

  setInterval(function() {
    col.insert({a:1}, function(err, r) {
      console.log("insert")
      console.log(err)

      col.findOne({}, function(err, doc) {
        console.log("findOne")
        console.log(err)
      });
    })
  }, 1000)
});

这个想法是运行此脚本,然后停止mongod,然后重新启动它. 所以,我们开始:

The idea is to run this script, and then stop mongod, and then restart it. So, here we go:

将MongoDb停止10秒钟可以达到预期的结果:它将在10秒钟内停止运行查询,然后在服务器返回ip后将运行所有查询

Stopping MongoDb for 10 seconds does the desired result: it will stop running the queries for those 10 seconds, and then will run all of them once the server is back ip

恰好30秒后,我开始得到:

After exactly 30 seconds, I start getting:

{ [MongoError: topology was destroyed] name: 'MongoError', message: 'topology was destroyed' }
insert

{ [MongoError: topology was destroyed] name: 'MongoError', message: 'topology was destroyed' }

问题在于,从此以后,当我重新启动mongod时,连接没有重新建立.

The trouble is that from this on, when I restart mongod, the connection is not re-establised.

这个问题有解决办法吗?如果是这样,您知道那是什么吗? 一旦我的应用开始呕吐拓扑已被破坏",让所有内容再次正常运行的唯一方法是重新启动整个应用...

Does this problem have a solution? If so, do you know what it is? Once my app starts puking "topology was destroyed", the only way to get everything to work again is by restarting the whole app...

推荐答案

有2个连接选项控制连接失败后mongo nodejs驱动程序如何重新连接

There are 2 connection options that control how mongo nodejs driver reconnects after connection fails

  • reconnectTries:尝试重新连接#次(默认30次)
  • reconnectInterval:服务器将在重试之间等待#毫秒 (默认为1000毫秒)
  • reconnectTries: attempt to reconnect #times (default 30 times)
  • reconnectInterval: Server will wait # milliseconds between retries (default 1000 ms)

关于mongo驱动程序文档的参考

这意味着mongo默认会继续尝试连接30次,并在每次重试前等待1秒.这就是为什么您在30秒后开始看到错误的原因.

Which means that mongo will keep trying to connect 30 times by default and wait 1 second before every retry. Which is why you start seeing errors after 30 seconds.

您应该根据需要调整这2个参数,例如本示例.

You should tweak these 2 parameters based on you needs like this sample.

var MongoClient = require('mongodb').MongoClient,
    f = require('util').format;

MongoClient.connect('mongodb://localhost:27017/test', 
    {
        // retry to connect for 60 times
        reconnectTries: 60,
        // wait 1 second before retrying
        reconnectInterval: 1000
    },

    function(err, db) {
        var col = db.collection('t');

        setInterval(function() {
            col.insert({
                a: 1
            }, function(err, r) {
                console.log("insert")
                console.log(err)

                col.findOne({}, function(err, doc) {
                    console.log("findOne")
                    console.log(err)
                });
            })
        }, 1000)
    });

这将尝试60次而不是默认的30次,这意味着当它停止尝试重新连接时,您将在60秒后开始看到错误.

This will try 60 times instead of the default 30, which means that you'll start seeing errors after 60 seconds when it stops trying to reconnect.

旁注:如果要阻止应用程序/请求在重新连接期到期之前等待,则必须传递选项bufferMaxEntries: 0.这样做的代价是,在短暂的网络中断期间,请求也会被中止.

Sidenote: if you want to prevent the app/request from waiting until the expiration of the reconnection period you have to pass the option bufferMaxEntries: 0. The price for this is that requests are also aborted during short network interruptions.

这篇关于可靠地重新连接到MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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