简体   繁体   English

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

[英]nodejs mongodb driver drops connection when idle

nodejs mongodb driver drops connection when idle and does not reconnect. nodejs mongodb驱动程序在空闲时会断开连接,并且不会重新连接。

Background 背景

The script below connects to mongodb and stores a reference to the database in a global variable "db" 下面的脚本连接到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);

});

Whenever i receive an insert request from client the following function is invoked: 每当我从客户端收到插入请求时,都会调用以下函数:

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

Issue 问题

When the server receives an insert request after a long time it fails silently or sometimes throws an error stating unable to insert object (Error: failed to connect to [host:port]) 服务器在很长一段时间后收到插入请求时,它会静默失败,有时会抛出错误,指出unable to insert object (Error: failed to connect to [host:port])

Question

Is there a way to prevent this behaviour? 有没有办法防止这种行为? I have tried to use auto_reconnect option and write concern of 1 but none of these have helped. 我试图使用auto_reconnect选项并写1的关注,但这些都没有帮助。

Thanks! 谢谢!

Solved! 解决了!

  1. Set server.socketoptions.keepAlive to 1 . 将server.socketoptions.keepAlive设置为1 Simply update the options object like so: 只需像这样更新options对象:

     options = { auto_reconnect: true, db: { w: 1 }, server: { socketOptions: { keepAlive: 1 } } }; 
  2. Ping the database at regular intervals. 定期对数据库执行ping操作。 Here's a code snippet that does exactly that: 这是一个精确地做到这一点的代码片段:

     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