nodejs mongodb驱动程序在空闲时丢弃连接

时间:2014-07-22 06:35:28

标签: node.js mongodb

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

背景

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

config = require("./config.js");
express = require("express");
mongodb = require("mongodb"); 

db = null;

options = {
  auto_reconnect: true,
  db: {
    w: 1
  }
};

mongodb.MongoClient.connect(config.mongo, options, function(err, database) {

  if (err !== null)
    return console.log(err);

  db = database;
  console.log("successfully connected to mongodb");

  db.on("close", (function() {
    return console.log("Connection to database closed automagically " + arguments);
  }));

  db.on("error", function(err) {
    return console.log("Db error " + err);
  });

  app.listen(port);

  return console.log("listening for connections on " + port);

});

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

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

问题

当服务器在很长一段时间后收到插入请求时,它会无声地失败,或者有时会抛出错误,说明unable to insert object (Error: failed to connect to [host:port])

问题

有没有办法防止这种行为?我试图使用auto_reconnect选项并写下1的关注但这些都没有帮助。

谢谢!

1 个答案:

答案 0 :(得分:4)

解决!

  1. Set server.socketoptions.keepAlive to 1。只需更新选项对象,如下所示:

    options = {
      auto_reconnect: true,
      db: {
        w: 1
      },
      server: {
        socketOptions: {
          keepAlive: 1
        }
      }
    };
    
  2. 定期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);
    };
    
相关问题