Node.js nodejs mongodb驱动程序在空闲时断开连接

Node.js nodejs mongodb驱动程序在空闲时断开连接,node.js,mongodb,Node.js,Mongodb,nodejs mongodb驱动程序在空闲时断开连接,不重新连接 背景 下面的脚本连接到mongodb,并将对数据库的引用存储在全局变量“db”中 每当我从客户端收到插入请求时,就会调用以下函数: insert = function(collectionName, object) { return db.collection(collectionName).insert(object, {w: 1}, (function(err) { return console.log("inse

nodejs mongodb驱动程序在空闲时断开连接,不重新连接

背景

下面的脚本连接到mongodb,并将对数据库的引用存储在全局变量“db”中

每当我从客户端收到插入请求时,就会调用以下函数:

insert = function(collectionName, object) {
  return db.collection(collectionName).insert(object, {w: 1}, (function(err) {
    return console.log("insert complete with err = " + err);
  }));
};
问题

当服务器在长时间后收到插入请求时,它会以静默方式失败,或者有时会抛出一个错误,说明无法插入对象(错误:无法连接到[主机:端口])

问题

有没有办法防止这种行为?我曾尝试使用auto_reconnect选项和写关注点1,但这些都没有帮助

谢谢

解决了

  • 。只需更新选项对象,如下所示:

    options = {
      auto_reconnect: true,
      db: {
        w: 1
      },
      server: {
        socketOptions: {
          keepAlive: 1
        }
      }
    };
    
  • 定期Ping数据库。下面是一段代码片段,它正是这样做的:

    printEventCount = function() {
      db.collection("IOSEvents").count(function(err, numberOfEvents) {
        console.log(new Date() + ": error = " + err + ", number of events = " + numberOfEvents);
        ping();
      });
    };
    
    ping = function() {
      if (config.pingPeriod === 0)
        return;    
      setTimeout(printEventCount, config.pingPeriod);
    };
    

  • 可能会帮助您保持冗余,至少,如果您预期某些连接会失败。然后,定期用无意义的“ping”检查池,您可以确认连接正在断开,然后在那里创建一些新的连接。我不确定它们是否会同时下降,或者以某种交错的方式下降,但这可能值得一试。从驱动程序2.1开始,您不需要显式设置auto_reconnect:true。socketOptions.keepAlive是一个数字(毫秒),不是布尔值。将其设置为1可能不是一个好主意。蒙古ABS建议30秒(30000)的设置:
    printEventCount = function() {
      db.collection("IOSEvents").count(function(err, numberOfEvents) {
        console.log(new Date() + ": error = " + err + ", number of events = " + numberOfEvents);
        ping();
      });
    };
    
    ping = function() {
      if (config.pingPeriod === 0)
        return;    
      setTimeout(printEventCount, config.pingPeriod);
    };