繁体   English   中英

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

[英]nodejs mongodb driver drops connection when idle

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. 将server.socketoptions.keepAlive设置为1 只需像这样更新options对象:

     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); }; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM