nodejs mongodb驱动程序在空闲时断开连接 [英] nodejs mongodb driver drops connection when idle
问题描述
nodejs mongodb驱动程序在空闲时会断开连接,并且不会重新连接.
nodejs mongodb driver drops connection when idle and does not reconnect.
背景
下面的脚本连接到mongodb并将对数据库的引用存储在全局变量"db"中
The script below connects to mongodb and stores a reference to the database in a global variable "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);
}));
};
问题
服务器在很长一段时间后收到插入请求时,它会静默失败,或者有时会抛出错误,指出unable to insert object (Error: failed to connect to [host:port])
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])
问题
是否有防止这种行为的方法?我试图使用auto_reconnect选项并写1的关注,但这些都没有帮助.
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.
谢谢!
推荐答案
已解决!
-
将server.socketoptions.keepAlive设置为1 .只需像这样更新options对象:
Set server.socketoptions.keepAlive to 1. Simply update the options object like so:
options = {
auto_reconnect: true,
db: {
w: 1
},
server: {
socketOptions: {
keepAlive: 1
}
}
};
定期对数据库执行ping操作.这是一个精确地做到这一点的代码片段:
Ping the database at regular intervals. 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);
};
这篇关于nodejs mongodb驱动程序在空闲时断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!