• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python使用pipeline批量读写redis的方法

python 搞代码 4年前 (2022-01-08) 42次浏览 已收录 0个评论

今天小编就为大家分享一篇python使用pipeline批量读写redis的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

用了很久的redis了。随着业务的要求越来越高。对redis的读写速度要求也越来越高。正好最近有个需求(需要在秒级取值1000+的数据),如果对于传统的单词取值,循环取值,消耗实在是大,有小伙伴可能考虑到多线程,但这并不是最好的解决方案,这里考虑到了redis特有的功能pipeline管道功能。

下面就更大家演示一下pipeline在python环境下的使用来源gaodai#ma#com搞*代#码网情况。

1、插入数据

 >>> import redis >>> conn = redis.Redis(host='192.168.8.176',port=6379) >>> pipe = conn.pipeline() >>> pipe.hset("hash_key","leizhu900516",8) Pipeline<ConnectionPool<Connection>> >>> pipe.hset("hash_key","chenhuachao",9) Pipeline<ConnectionPool<Connection>> >>> pipe.hset("hash_key","wanger",10) Pipeline<ConnectionPool<Connection>> >>> pipe.execute() [1L, 1L, 1L] >>> 

2、批量读取数据

 >>> pipe.hget("hash_key","leizhu900516") Pipeline<ConnectionPool<Connection>> >>> pipe.hget("hash_key","chenhuachao") Pipeline<ConnectionPool<Connection>> >>> pipe.hget("hash_key","wanger") Pipeline<ConnectionPool<Connection>> >>> result = pipe.execute() >>> print result ['8', '9', '10']  #有序的列表 >>> 

总结:redis的pipeline就是这么简单,实际生产环境,根据需要去编写相应的代码。思路同理,如:

 redis_db = redis.Redis(host='127.0.0.1',port=6379) data = ['zhangsan', 'lisi', 'wangwu'] with redis_db.pipeline(transaction=False) as pipe: for i in data: pipe.zscore(self.key, i) result = pipe.execute() print result # [100, 80, 78] 

线上的redis一般都是集群模式,集群模式下使用pipeline的时候,在创建pipeline的对象时,需要指定

 pipe =conn.pipeline(transaction=False)

经过线上实测,利用pipeline取值3500条数据,大约需要900ms,如果配合线程or协程来使用,每秒返回1W数据是没有问题的,基本能满足大部分业务。

以上就是python使用pipeline批量读写redis的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python使用pipeline批量读写redis的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址