Fork me on GitHub

pool连接池

安装generic-pool

1
npm i --save generic-pool

mysql连接池

wulian-mysql

mngodb连接池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
var Pool = require('generic-pool').Pool;
var md5 = require('wulian-common').md5;
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
const db = {};
const createPool = (key, options) => {
db[key] = new Pool({
name: 'mysql',
create: function(callback) {
var mongodb = new Db(options.db, new Server(options.host, options.port), {safe: true, poolSize: 1});
mongodb.open(function (err, db) {
callback(err, db);
})
},
destroy: (mongodb) => { mongodb.close(); },
max: options.connectionLimit || 10,
// optional. if you set this, make sure to drain() (see step 3)
min: options.connectionLimitMin || 0,
// specifies how long a resource can stay idle in pool before being removed
idleTimeoutMillis: 30000,
// if true, logs via console.log - can also be a function
log: process.env.DEBUG !== undefined
});
};
/**
* 创建连接池
* @param {obj} options Mongodb连接参数
* @return {obj} Mongodb Pool
*/
module.exports = function (options, logger = console.log) {
const key = md5(JSON.stringify(options));
if (!db[key]) {
createPool(key, options);
}
return db[key];
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var Db = require('./db');
const pool = new Db({
cookieSecret: 'myblog',
db: 'blog',
host: 'localhost',
port: 27017
});
pool.acquire(function(err, db) {
if (err) {
console.log(err);
} else {
db.collection('users').save({test:1},function(err,result){
pool.release(db);
});
}
});
-------------本文结束感谢您的阅读-------------
如果您觉得受益了,欢迎打赏鼓励。