[英]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的關注,但這些都沒有幫助。
謝謝!
解決了!
將server.socketoptions.keepAlive設置為1 。 只需像這樣更新options對象:
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); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.