用了好久的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數據是沒有問題的,基本能知足大部分業務。線程