python使用pipeline批量讀寫redis的方法
用了很久的redis了。隨著業(yè)務的要求越來越高。對redis的讀寫速度要求也越來越高。正好最近有個需求(需要在秒級取值1000+的數(shù)據(jù)),如果對于傳統(tǒng)的單詞取值,循環(huán)取值,消耗實在是大,有小伙伴可能考慮到多線程,但這并不是最好的解決方案,這里考慮到了redis特有的功能pipeline管道功能。
下面就更大家演示一下pipeline在python環(huán)境下的使用情況。
1、插入數(shù)據(jù)
>>> 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]
>>>
2、批量讀取數(shù)據(jù)
>>> 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就是這么簡單,實際生產(chǎn)環(huán)境,根據(jù)需要去編寫相應的代碼。思路同理,如:
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的時候,在創(chuàng)建pipeline的對象時,需要指定
pipe =conn.pipeline(transaction=False)
經(jīng)過線上實測,利用pipeline取值3500條數(shù)據(jù),大約需要900ms,如果配合線程or協(xié)程來使用,每秒返回1W數(shù)據(jù)是沒有問題的,基本能滿足大部分業(yè)務。
以上這篇python使用pipeline批量讀寫redis的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用Python進行數(shù)據(jù)清洗和預處理的實現(xiàn)代碼
Python作為數(shù)據(jù)科學領域的熱門編程語言,提供了豐富的庫和工具來處理和清洗數(shù)據(jù),本文將介紹如何使用Python進行數(shù)據(jù)清洗和預處理,并提供相應的代碼示例,需要的朋友可以參考下2024-05-05
python根據(jù)京東商品url獲取產(chǎn)品價格
閑著沒事嘗試抓一下京東的數(shù)據(jù),需要使用到的庫有:BeautifulSoup,urllib2,在Python2下測試通過2015-08-08
python 實現(xiàn)將txt文件多行合并為一行并將中間的空格去掉方法
今天小編就為大家分享一篇python 實現(xiàn)將txt文件多行合并為一行并將中間的空格去掉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
pandas實現(xiàn)按照多列排序-ascending
這篇文章主要介紹了pandas實現(xiàn)按照多列排序-ascending,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

