我打开一个与Mongo DB的连接。在加载测试后,我可以看到从我的应用程序到Db的多个打开的连接。
以下是代码:
var app = require('express')();
var logger = require('log4js').getLogger();
var async = require('async');
const logConnStr = 'mongodb://mysite.com/logs';
const AppPort = 10000;
logger.debug("Connecting to DB...");
function connectToLogs(cb) {
MongoClient.connect(logConnStr, { server: {reconnectTries: 3000} }, function(err, db) {
if ( err )
return cb(err);
cb(null, db);
});
}
function getRoot(req, res) {
var dbLogs = req.app.locals.dbLogs;
dbLogs.collection('banners').count( function( err, count ) {
if ( err )
return res.json({status: false, result: err} );
logger.debug(`Returning ${count}`);
res.json({status: true, result: count} );
});
}
function onDbInit(err, dbs) {
assert.equal(err, null);
logger.debug("Connected.");
app.locals.dbLogs = dbs[0];
app.get('/', getRoot);
app.listen(AppPort);
logger.debug(`Listening on ${AppPort}, pid=${process.pid}`);
}
async.series([
connectToLogs
], onDbInit);
运行应用程序时,MongoDB的连接数为1,正如预期的那样:
[root@njs ~]# lsof -p 19199 | grep TCP
node 19199 root 12u IPv4 3024199246 0t0 TCP aaa.xxx.yyy.zzz:53535->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
node 19199 root 13u IPv4 3024199307 0t0 TCP *:ndmp (LISTEN)
[root@njs ~]#
然后我用围攻加载测试应用程序:
siege -r 10 -c 10 aaa.xxx.yyy.zzz:10000
再次运行losof
:
[root@njs ~]# lsof -p 19199 | grep TCP
node 19199 root 12u IPv4 3024199246 0t0 TCP aaa.xxx.yyy.zzz:53535->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
node 19199 root 13u IPv4 3024199307 0t0 TCP *:ndmp (LISTEN)
node 19199 root 14u IPv4 3024238770 0t0 TCP aaa.xxx.yyy.zzz:53752->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
node 19199 root 15u IPv4 3024238914 0t0 TCP aaa.xxx.yyy.zzz:53758->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
node 19199 root 17u IPv4 3024238779 0t0 TCP aaa.xxx.yyy.zzz:53754->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
node 19199 root 18u IPv4 3024238824 0t0 TCP aaa.xxx.yyy.zzz:53756->aaa.xxx.yyy.zzz:27017 (ESTABLISHED)
[root@njs ~]#
这些联系来自哪里?
测试系统:
CentOS6,NodeJS 5.8.0,MongoDB 3.2 WiredTiger,NodeJS MongoDB驱动程序2.1.7