【问题标题】:MongoDB: >5 open connections for a single db handlerMongoDB:单个数据库处理程序的 >5 个打开连接
【发布时间】:2013-01-29 23:12:53
【问题描述】:

我是 nodejs 和 mongdb 的新手,我将在我的一个项目中使用它们,一旦我的 db 连接正常工作,我很震惊地看到我的代码确实有多少数据库连接。所以,给定这个简单的 sn-p 代码:

var express = require('express');
var mongo = require('mongodb');  
var app = express();

// Further details:
// nodejs: v0.8.18
// mongod: v2.2.2
// node's mongodb driver: v1.2.10

app.get('/', function(req, res){
    res.send('<h1>Ok</h1>');
});

var setUp = function() {   
    // get a handler to the testDB Database
    mongo.Db.connect('mongodb://localhost:27017/testDB', function(err, db) {
        if (err)
            throw err;
        // create a test collection in the database
        db.createCollection('test', function(err, test) {
            if (err)
                throw err;
            // insert a dummy document into the test collection          
            test.insert({'name':'admin', 'pass':'admin'});

            app.listen(3000); 
            console.log('App listening on port 3000');
        });
    });
}

setUp();

当 nodejs 进程启动时,mongo 守护进程会输出这段日志:

... connection accepted from 127.0.0.1:40963 #34 (1 connection now open)
... connection accepted from 127.0.0.1:40964 #35 (2 connections now open)
... connection accepted from 127.0.0.1:40965 #36 (3 connections now open)
... connection accepted from 127.0.0.1:40966 #37 (4 connections now open)
... connection accepted from 127.0.0.1:40967 #38 (5 connections now open)
... connection accepted from 127.0.0.1:40968 #39 (6 connections now open)
... end connection 127.0.0.1:40963 (5 connections now open)
... allocating new datafile /var/data/testDB.ns, filling with zeroes...
...

进程终止时的这个:

... connection 127.0.0.1:40964 (4 connections now open)
... connection 127.0.0.1:40965 (3 connections now open)
... connection 127.0.0.1:40966 (2 connections now open)
... connection 127.0.0.1:40967 (1 connection now open)
... connection 127.0.0.1:40968 (0 connections now open)

mongo 驱动程序是否真的需要与 mongod 建立如此多的连接才能获得单个 db 处理程序,或者我实现此的方式有什么问题?我真的希望在那里只看到一个打开的连接...

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    Db.connect 默认打开一个包含 5 个连接的池。如果您想将其限制为单个连接,您可以通过 server 选项执行此操作,如下所示:

    mongo.Db.connect(
        'mongodb://localhost:27017/testDB', 
        {server: {poolSize: 1}}, 
        function(err, db) { ...
    

    【讨论】:

    • 哦,我明白了。谢谢约翰尼,这成功了。这些池连接有什么用?
    • 它们允许多个查询并行发生。对于可扩展的网站非常重要。
    【解决方案2】:

    你也可以这样传

    var mongoclient = new mongodb.MongoClient(new mongodb.Server(
        'localhost', 27017, {'native_parser': true, 'poolSize': 1} 
    ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-10
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多