当连接达到130个打开的连接时,Node.js mongodb错误

时间:2013-05-28 06:09:45

标签: apache node.js mongodb

这是我正在使用的请求示例:

app.get('/', function (req, res) {
     var user_hash = req.cookies.SESSION;

    db.connect(mongoURI, function (err, db) {
        var collection = db.collection('sessions');

        collection.findOne({hash: user_hash}, function (err, item) {
            res.render('index', {title: 'Домашняя страница', session: item !== null});
            db.close();
        });
    });
});

而且我有很多请求像这样的人。

当我在Apache Benchmark中执行以下命令时出现问题:

ab -n 100 -c100 http://127.0.0.1:8080

我发现了以下错误:

cannon read property collection of null

我的猜测是,在apache基准测试之后,在mongodb上打开的连接是130 - 150。 现在我正试图让我的服务器进入“战斗”更加稳定。 我听说过连接池,但无法弄明白。

现在问题: 我的服务器崩溃因为“mongodb上许多打开的连接”或其他一些东西? 我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

持续打开和关闭与后端数据库的连接并不是一个好习惯,因为将资源返回到操作系统需要一些时间。这可能解释了为什么你看到错误。

您可以按照here所述增加mongod或mongos的ulimit,但考虑到您尝试进行的测试类型,我仍然认为您的资源已经耗尽。

使用mongoose或方法described here等内容可能更有意义。

但是如果你真的想要遵循当前的方法,你应该包装你的快递申请:

Db.connect(mongoURI,function(err, db){
  if(err) {
    console.log("Error " , err);
    return;
  }
  var collection = db.collection('sessions');

  app.get('/', function (req, res) {
    var user_hash = req.cookies.SESSION;
    collection.findOne({hash: user_hash}, function (err, item) {
        res.render('index', {title: 'Домашняя страница', session: item !== null});
    });
  });

});