用了好久的redis了。随着业务的要求愈来愈高。对redis的读写速度要求也愈来愈高。正好最近有个需求(须要在秒级取值1000+的数据),若是对于传统的单词取值,循环取值,消耗实在是大,有小伙伴可能考虑到多线程,但这并非最好的解决方案,这里考虑到了redis特有的功能pipeline管道功能。下面就更你们演示一下pipeline在python环境下的使用状况。python
一、插入数据
redis
>>> import redis >>> conn = redis.Redis(host='192.168.8.176',port=6379) >>> pipe = conn.pipeline() >>> pipe.hset("hash_key","leizhu900516",8) Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> pipe.hset("hash_key","chenhuachao",9) Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> pipe.hset("hash_key","wanger",10) Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> pipe.execute() [1L, 1L, 1L] >>> 查看插入的结果:如图
二、批量读取数据多线程
>>> pipe.hget("hash_key","leizhu900516") Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> pipe.hget("hash_key","chenhuachao") Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> pipe.hget("hash_key","wanger") Pipeline<ConnectionPool<Connection<host=192.168.8.176,port=6379,db=0>>> >>> result = pipe.execute() >>> print result ['8', '9', '10'] #有序的列表 >>>
总结:redis的pipeline就是这么简单,实际生产环境,根据须要去编写相应的代码。思路同理。线上的redis通常都是集群模式,集群模式下使用pipeline的时候,在建立pipeline的对象时,须要指定ide
pipe =conn.pipeline(transaction=False)
通过线上实测,利用pipeline取值3500条数据,大约须要900ms,若是配合线程or协程来使用,每秒返回1W数据是没有问题的,基本能知足大部分业务。线程