python使用pipeline讀寫redis

用了很久的redis了。隨着業務的要求越來越高。對redis的讀寫速度要求也越來越高。正好最近有個需求(需要在秒級取值1000+的數據),如果對於傳統的單詞取值,循環取值,消耗實在是大,有小夥伴可能考慮到多線程,但這並不是最好的解決方案,這裏考慮到了redis特有的功能pipeline管道功能。下面就更大家演示一下pipeline在python環境下的使用情況。

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<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]
>>> 
查看插入的結果:如圖

wKioL1eElAnAbWYLAAEXcklxX2c229.png-wh_50

2、批量讀取數據

>>> 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的對象時,需要指定

pipe =conn.pipeline(transaction=False)

經過線上實測,利用pipeline取值3500條數據,大約需要900ms,如果配合線程or協程來使用,每秒返回1W數據是沒有問題的,基本能滿足大部分業務。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章