標籤:python
一、安裝服務
下載、編譯安裝
wget http://download.redis.io/releases/redis-3.0.1.tar.gztar -zxvf redis-3.0.1.tar.gzcd redis-3.0.1make
二進位檔案是編譯完成後在src目錄下,通過下面的命令啟動Redis服務:
$ src/redis-server &
用戶端也可以如下安裝:
pip install redis
二、redis串連樣本
redis是以key-value的形式儲存的。首先我們將redis所在主機的ip和發布連接埠作為參數執行個體化了一個對象r,然後去設定set和取出get值。
例子:
import redisredis_config = {"host": "192.168.2.230","port": 6379}r = redis.Redis(**redis_config)r.set("name","huangzhenping")print(r.keys())print(r.get("name"))
運行結果:
name
huangzhenping
三、串連池
redis-py使用connection pool來管理對一個redis server的所有串連,避免每次建立、釋放串連的開銷。預設,每個Redis執行個體都會維護一個自己的串連池。可以直接建立一個串連池,然後作為參數Redis,這樣就可以實現多個Redis執行個體共用一個串連池
例子:
import redisredis_config = { "host": "192.168.2.230", "port": 6379}pool = redis.ConnectionPool(**redis_config)r = redis.Redis(connection_pool=pool)r.set("age","27")print(r.get("age"))
運行結果:
27
或者將串連池封裝成一個函數,方便調用:
import redisdef get_redis_connect(): redis_config = { "host": "192.168.2.230", "port": 6379 } pool = redis.ConnectionPool(**redis_config) r = redis.Redis(connection_pool=pool) return r if __name__ == "__main__": r = get_redis_connect() print(r.keys())
四、管道
redis-py預設在執行每次請求都會建立(串連池申請串連)和斷開(歸還串連池)一次串連操作,如果想要在一次請求中指定多個命令,則可以使用pipline實現一次請求指定多個命令,並且預設情況下一次pipline 是原子性操作。redis服務端會處理完多條命令後會將多條命令的處理結果打包到一起返回給用戶端。需要注意到是redis必須在處理完所有命令前先緩衝起所有命令的處理結果,打包的命令越多,緩衝消耗記憶體也越多。
例子:對比使用管道和不使用管道處理的時間
import redisimport datetimedef withpipe(r): pipe = r.pipeline(transaction=True) for i in xrange(1, 1000): key = "key1_" + str(i) value = "value1_" + str(i) pipe.set(key, value) pipe.execute() def withoutpipe(r): for i in xrange(1, 1000): key = "key2_" + str(i) value = "value2_" + str(i) r.set(key, value) redis_config = { "host": "192.168.2.230", "port": 6379, "db": 0}if __name__ == "__main__": pool = redis.ConnectionPool(**redis_config) r1 = redis.Redis(connection_pool=pool) r2 = redis.Redis(connection_pool=pool) start = datetime.datetime.now() withpipe(r1) end = datetime.datetime.now() t_time = (end - start).microseconds print("withpipe time is: {0}".format(t_time)) start = datetime.datetime.now() withoutpipe(r2) end = datetime.datetime.now() t_time = (end - start).microseconds print("withoutpipe time is: {0}".format(t_time))
運行結果:
withpipe time is: 17000
withoutpipe time is: 105000
python串連redis