官网:http://github.com/coopernurse/node-pool
var poolModule = bbPromise.promisifyAll(require('generic-pool'))
var redispool = poolModule.Pool({
name : 'redis',
create : function(callback) {
var client = Redis.createClient(configs.dbconfig.dbredis.port,
configs.dbconfig.dbredis.host)
callback(null, client)
},
destroy : function(client) { client.quit()},
max : 10,
// optional. if you set this, make sure to drain() (see step 3)
min : 2,
// 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 : true
})
function getRedisClient() {
return redispool.acquireAsync().disposer(function(client, promise) {
console.log("redispool.release(client)")
redispool.release(client)
})
}
dbs.redisclient = getRedisClient
建议使用中间件连接,操作数据库的代码更加简单。我们的后台接口就是用的中间件连接。nodejs的设计特点,使得他本身就很快,即使是读写数据库这样耗时的操作。用连接池的目的其实就是想就加快数据库的IO速度。因此如果用nodejs,使用普通连接足矣!generic-pool模块是nodejs的一个第三方模块,其作用为提供一个通用的连接池模块,可以通过generic-pool实现对tcp连接池或者MySQL数据库连接池等的管理。github的地址如下:https://github.com/coopernurse/node-pool// Create a MySQL connection pool with
// a max of 10 connections, a min of 2, and a 30 second max idle time
var Pool = require('generic-pool').Pool
var mysql = require('mysql')// v2.10.x
var pool = new Pool({
name : 'mysql',
create : function(callback) {
var c = mysql.createConnection({
user: 'scott',
password: 'tiger',
database:'mydb'
})
// parameter order: err, resource
callback(null, c)
},
destroy : function(client) { client.end()},
max : 10,
// optional. if you set this, make sure to drain() (see step 3)
min : 2,
// 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 : true
})