您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)python如何使用pipeline批量讀寫redis,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
用了很久的redis了。隨著業(yè)務(wù)的要求越來越高。對redis的讀寫速度要求也越來越高。正好最近有個(gè)需求(需要在秒級(jí)取值1000+的數(shù)據(jù)),如果對于傳統(tǒng)的單詞取值,循環(huán)取值,消耗實(shí)在是大,有小伙伴可能考慮到多線程,但這并不是最好的解決方案,這里考慮到了redis特有的功能pipeline管道功能。
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'] #有序的列表 >>>
總結(jié):redis的pipeline就是這么簡單,實(shí)際生產(chǎn)環(huán)境,根據(jù)需要去編寫相應(yīng)的代碼。思路同理,如:
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的時(shí)候,在創(chuàng)建pipeline的對象時(shí),需要指定
pipe =conn.pipeline(transaction=False)
經(jīng)過線上實(shí)測,利用pipeline取值3500條數(shù)據(jù),大約需要900ms,如果配合線程or協(xié)程來使用,每秒返回1W數(shù)據(jù)是沒有問題的,基本能滿足大部分業(yè)務(wù)。
關(guān)于“python如何使用pipeline批量讀寫redis”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。