首页 > nodejs使用mongodb连接池

nodejs使用mongodb连接池

在开发中想使用连接池 在网上找到了一段代码 但是自己测试的时候发现了些问题 当我把setTimeout中的语句数量变成五条以上的时候 nodejs会首先执行五条 然后过一段时间才会执行剩下的 而且好像server_options的pool_size:1好像也没有奇效 不知道这个是什么问题 要怎么做修改 代码如下:

var http=require('http'),
    mongodb = require("mongodb"),
    poolModule = require('generic-pool');

var pool = poolModule.Pool({
    name     : 'mongodb',
    create   : function(callback) {
        var server_options={'auto_reconnect':false,poolSize:1};
        var db_options={w:-1};
        var mongoserver = new mongodb.Server('localhost', 27017,server_options );
        var db=new mongodb.Db('test', mongoserver, db_options);
        db.open(function(err,db){
            if(err)return callback(err);
            callback(null,db);
        });
    },
    destroy  : function(db) { db.close(); },
    max      : 10,
    idleTimeoutMillis : 30000,
    log : false 
});

var server=http.createServer(function(req,res){
    pool.acquire(function(err, db) {
        if (err) {
            res.statusCode=500;
            res.end(JSON.stringify(err,null,2));
        } else {
            db.collection('foo').save({test:1},function(err,result){
                res.end(JSON.stringify(result,null,2));
                pool.release(db);
            });
        }
    });
});
server.listen(8080,function(){
    console.log('server listen to %d',this.address().port);
});
setTimeout(function(){
    http.get('http://localhost:8080',function(res){console.log('request ok')});
    http.get('http://localhost:8080',function(res){console.log('request ok')});
},2000);

其实你的问题跟 mongodb 和连接池都没有关系,是你的测试方法不对。

http.get 默认最多同时发起 5 个请求,超过的请求会排队。你如果需要更多请求,修改 http.globalAgent.maxSockets 的值就行,比如 20。

你的 http.get 调用写的也有问题,你需要用下面代码把 res 全部数据读完 http.get 才会释放连接:

res.on('data', function (chunk) {
    // use chunk
});

另外,如果我没记错的话,通过 mongodb.Server 创建的实例本身就是带连接池的,连接池大小通过 poolSize 设置。你直接从这个 server 不断创建 db 并使用就行,不需要手动创建并管理多个 server 实例,多此一举了。

【热门文章】
【热门文章】