gpt4 book ai didi

node.js - nodejs mongodb驱动程序在空闲时断开连接

转载 作者:IT老高 更新时间:2023-10-28 12:29:57 24 4
gpt4 key购买 nike

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. Set server.socketoptions.keepAlive to 1 .只需像这样更新选项对象:

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

关于node.js - nodejs mongodb驱动程序在空闲时断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com