Redis pipline

来源:互联网 发布:sql语句union all 编辑:程序博客网 时间:2024/05/15 16:20

1. 简介
Redis本身是一个cs模式的tcp server, client可以通过一个socket连续发起多个请求命令。 每个请求命令发出后client通常会阻塞并等待redis服务端处理,redis服务端处理完后将结果返回给client。
redis的pipeline(管道)功能在命令行中没有,但redis是支持pipeline的,而且在各个语言版的client中都有相应的实现。 由于网络开销延迟,即算redis server端有很强的处理能力,也由于收到的client消息少,而造成吞吐量小。当client 使用pipelining 发送命令时,redis server必须部分请求放到队列中(使用内存)执行完毕后一次性发送结果;如果发送的命名很多的话,建议对返回的结果加标签,当然这也会增加使用的内存;
Pipeline在某些场景下非常有用,比如有多个command需要被“及时的”提交,而且他们对相应结果没有互相依赖,而且对结果响应也无需立即获得,那么pipeline就可以充当这种“批处理”的工具;而且在一定程度上,可以较大的提升性能,性能提升的原因主要是TCP链接中较少了“交互往返”的时间。不过在编码时请注意,pipeline期间将“独占”链接,此期间将不能进行非“管道”类型的其他操作,直到pipeline关闭;如果你的pipeline的指令集很庞大,为了不干扰链接中的其他操作,你可以为pipeline操作新建Client链接,让pipeline和其他正常操作分离在2个client中。不过pipeline事实上所能容忍的操作个数,和socket-output缓冲区大小/返回结果的数据尺寸都有很大的关系;同时也意味着每个redis-server同时所能支撑的pipeline链接的个数,也是有限的,这将受限于server的物理内存或网络接口的缓冲能力。
python 测试代码:
同时提交100000个command:

2. 测试
连接本机redis-server:

#!/usr/bin/python2import redisimport timedef without_pipeline():    r = redis.Redis()    for i in range(100000):        r.ping()    returndef with_pipeline():    r = redis.Redis()    pipeline = r.pipeline()    for i in range(100000):        pipeline.ping()    pipeline.execute()    returndef bench(desc):    start = time.clock()    desc()    stop = time.clock()    diff = stop-start    print "%s has token %s" % (desc.func_name, str(diff))if __name__ == '__main__':    bench(without_pipeline)    bench(with_pipeline)

测试结果:

[root@node1 python]# python redis-pipline.py without_pipeline has token 6.15with_pipeline has token 0.85

在本机没有网络开销的情况下差距为时间差距为8倍。

远程redis-server测试,以网易云redis实例为例:

#!/usr/bin/python2import redisimport timehost = "10.173.32.198"port = 6379db = 0 password = "123321"def without_pipeline():    r = redis.Redis(host = host, port = port, db = db, password = password)    for i in range(100000):        r.ping()    returndef with_pipeline():    r = redis.Redis(host = host, port = port, db = db, password = password)    pipeline = r.pipeline()    for i in range(100000):        pipeline.ping()    pipeline.execute()    returndef bench(desc):    start = time.clock()    desc()    stop = time.clock()    diff = stop-start    print "%s has token %s" % (desc.func_name, str(diff))if __name__ == '__main__':    bench(without_pipeline)    bench(with_pipeline)

测试结果:

[root@node1 python]# python redis-pipline.py without_pipeline has token 11.23with_pipeline has token 0.8

使用vpn连接网易云的redis实例时间差距约为14倍。

小结:可见pipline 效果还是很明显的。

参考: http://weipengfei.blog.51cto.com/1511707/1215042

原创粉丝点击