node.js中如何配置redis与连接池?

node.js中如何配置redis与连接池?,第1张

node.js中配置连接池可以考虑使用generic-pool模块

官网: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

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

})

nodejs是个单线程的过程,异步处理很方便,redis又支持pipelining,通过异步处理,可以在复用一个连接的情况下完成大部分任务。返回顺序上,redis的请求永远都是先请求的先返回,所以负责发送的程序在发送的时候记个序号,然后按序号等相应返回结果就行了。不过吧,我觉得如果要用BRPOP这样的命令,没有连接池肯定不行啊……还有如果要用PUB/SUB的话,Subscribe也要占一个连接。

一般考虑用单连接还是多连接,主要看两个问题:

1. 我自己的程序是多线程还是单线程,如果是多线程,用多个连接、每个线程一个连接,编程起来要简单很多,可以直接使用同步socket的方式;单线程一般本身就是多路复用,用多个连接跟使用pipelining的编程复杂度是一样的。

2. 服务器端使用多个连接是否可以提高性能。这个取决于服务器端对pipelining(或者multiplexing)的支持。redis对pipelining的支持很好,用多个连接完全不能比单个连接快,只会占用更多的资源,所以尽量应当使用单个连接。而MySQL这样的协议对pipelining比较不友好,它是有状态转移的,在处理一个SQL的过程中可能需要发送/取回多次数据,这样只能一次处理一个SQL,用多个连接就可以有效提高并发度。其他协议也是一样的,比如HTTP/1.1虽然支持pipelining但是只能一个一个结果返回,而HTTP/2.0对multiplexing的支持很好,这样HTTP/1.1就应当使用多个连接,而HTTP/2.0就可以使用单连接。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/6848146.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-29
下一篇 2023-03-29

发表评论

登录后才能评论

评论列表(0条)

保存