nodejs mongodb驱动程序在闲置时断开连接
nodejs mongodb驱动程序在闲置时断开连接并且不重新连接。
背景
下面的脚本连接到mongodb并在全局variables“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的关注,但没有一个帮助。
谢谢!
解决了!
-
将server.socketoptions.keepAlive设置为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); };