由官方文檔而得
python 利用 redis 第三方庫
首先安裝
pip install redis
然后就可以開始愉快地使用了
import redis
r = redis.StricRedis(host='localhost', port=6379, db=0)
r.set('test', '1')
r.get('test') # ->> '1'
注,r 方法一覽:


默認(rèn)情況下,響應(yīng)以 Python3 的字節(jié)Python 2 的 str 形式返回,用戶負(fù)責(zé)解碼操作。
redis-py 實(shí)現(xiàn)了兩個(gè)類來操作 redis
-
StricRedis盡量堅(jiān)持官方語法,除了以下命令:-
select沒有實(shí)現(xiàn),考慮到了線程安全 -
delPython 關(guān)鍵字,用delete代替 -
config get|se作為config_get / config_set實(shí)現(xiàn) -
multi / exec作為Pipeline類的一部分實(shí)現(xiàn)的。
-
-
Redis類是StricRedis的子類,提供向后的兼容性。推薦使用StricRedis。Redis 覆蓋了幾個(gè)命令:-
lremnum 和 value 參數(shù)順序顛倒,num 提供默認(rèn)值 0 -
zaddRedis類期望* args的形式為:name1,score1,name2,score2,...,而 StricRedis 是score1,name1,score2,name2,...,這與 Redis 一樣。 -
setextime 和 value 順序顛倒。在 Redis 類中是:setex(key, value, time),在 StricRedis 類中是:setex(key, time, value)。
-
連接池來操作
pool = redis.ConnectionPool(host = ' localhost ',port = 6379,db = 0)
r = redis.Redis(connection_pool = pool)
解析器
可以使用 Redis 官方維護(hù)的一個(gè) C 庫 hiredis
pip install hiredis
線程安全
可以在線程之間安全地共享 Redis 客戶端實(shí)例。有一點(diǎn)需要注意:Redis SELECT命令。SELECT命令允許您切換連接當(dāng)前使用的數(shù)據(jù)庫。該數(shù)據(jù)庫保持選定狀態(tài)直到選擇另一個(gè)數(shù)據(jù)庫或連接關(guān)閉。這會(huì)產(chǎn)生一個(gè)問題,即連接可以返回到連接到不同數(shù)據(jù)庫的池。因此不會(huì)實(shí)現(xiàn) select 命令。
在線程之間傳遞PubSub或Pipeline對象是不安全的。
管道
一般用來執(zhí)行事務(wù)操作
>>> r = redis.Redis(...)
>>> r.set('bing', 'baz')
>>> # Use the pipeline() method to create a pipeline instance
>>> pipe = r.pipeline()
>>> # The following SET commands are buffered
>>> pipe.set('foo', 'bar')
>>> pipe.get('bing')
>>> # the EXECUTE call sends all buffered commands to the server, returning
>>> # a list of responses, one for each command.
>>> pipe.execute()
[True, 'baz']
也可以進(jìn)行鏈?zhǔn)讲僮?/p>
>>> pipe.set(' foo ',' bar ').sadd(' faz ',' baz ').incr(' auto_number ')。execute()
[True,True,6]
禁用原子性:
pipe = r.pipeline(transaction = False)
WATCH 監(jiān)控命令:
>>> with r.pipeline() as pipe:
... while 1:
... try:
... # 設(shè)置一個(gè) watch
... pipe.watch('OUR-SEQUENCE-KEY')
... current_value = pipe.get('OUR-SEQUENCE-KEY')
... next_value = int(current_value) + 1
... # 開始事務(wù)
... pipe.multi()
... pipe.set('OUR-SEQUENCE-KEY', next_value)
... # 執(zhí)行
... pipe.execute()
... # 如果拋出 WatchError ,表示原子性失敗
... break
... except WatchError:
... # 另一個(gè)客戶端修改了,我們必須重試
... continue
由于 Pipeline 在 watch 期間綁定到單個(gè)連接,必須調(diào)用 reset() 來確保返回連接池,使用 with 上下文的話,它會(huì)自動(dòng)調(diào)用。當(dāng)然也可以手動(dòng)調(diào)用:
>>> pipe = r.pipeline()
>>> while 1:
... try:
... pipe.watch('OUR-SEQUENCE-KEY')
... ...
... pipe.execute()
... break
... except WatchError:
... continue
... finally:
... pipe.reset()
也可以使用 transaction() 方法來簡化操作
>>> def client_side_incr(pipe):
... current_value = pipe.get('OUR-SEQUENCE-KEY')
... next_value = int(current_value) + 1
... pipe.multi()
... pipe.set('OUR-SEQUENCE-KEY', next_value)
>>>
>>> r.transaction(client_side_incr, 'OUR-SEQUENCE-KEY')
[True]
注:訂閱發(fā)布模式還沒有詳細(xì)理解,故沒寫,以后用到了會(huì)寫。
迭代器
>>> for key, value in (('A', '1'), ('B', '2'), ('C', '3')):
... r.set(key, value)
>>> for key in r.scan_iter():
... print key, r.get(key)
A 1
B 2
C 3