nodejs 链接 redis/mysql 连接池
redis是单线程作业,所以不管查询任务是由一个链接发来的还是多个链接发来的,redis是串行的执行。并通过当前的链接返回客户端。nodejs接受redis的返回后,不管是不是并行,都要等主线程空闲下来才能一个个处理服务器返回的数据。
再看mysql~
mysql不是单线程服务的,可以并行处理多个查询请求。
mysql会为每一个链接创建一个单独的线程查询。redis数据基本在内存中,mysql会大量的读取磁盘的I/O,多线程比较快。
但是nodejs是单线程的。但是它调用的I/O指令等是通过另外的线程做的,I/O指令完成后就给主线程小任务,回调函数。
nodejs主线程一个,但是IO线程会有多个。
nodejs 使用多个连接来连接mysql。多连接是需要连接池的,有连接池就避免了每次连接都要去创建销毁的消耗了。
综上:nodejs + mysql用线程池是没什么问题的。nodejs + redis只用单个连接就够。
所以有了连接管理模块,egg-redis。
redis性能
错误原因:redis client的业务代码以及redis client的I/O性能。
redis client采用的是单链接模式,底层采用的非阻塞网络I/O,
调优:pipeline,script
无依赖批量请求采用pipeline。
redis高性能体现在服务端处理能力,但瓶颈往往出现在客户端,因此增强客户端I/O能力与并发并行多客户端才是高并发解决方案。
ioredis
性能为中心,功能齐全的,支持Redis >= 2.6.12 and (Node.js >= 6).
npm install ioredis
basic usage
var Redis = require('ioredis');
var redis = new Redis();
redis.set('foo', 'bar');
redis.get('foo', function (err, result) {
console.log(result);
});
// Or using a promise if the last argument isn't a function
redis.get('foo').then(function (result) {
console.log(result);
});
// Arguments to commands are flattened, so the following are the same:
redis.sadd('set', 1, 3, 5, 7);
redis.sadd('set', [1, 3, 5, 7]);
// All arguments are passed directly to the redis server:
redis.set('key', 100, 'EX', 10);
Connect to Redis
new Redis() // Connect