安裝的Python版本 3.6.1
redis安裝的2.8
安裝redis模塊
pip install redis
簡單使用
redis-test.py
import redis r=redis.Redis(host='127.0.0.1',port=6609,db=0) r.set('name','baby') print(r.get('name')) print(r.dbsize())
使用connection pool來管理對一個redis server的所有連接,避免每次建立、釋放連接的開銷。
默認,每個Redis實例都會維護一個自己的連接池。
可以直接建立一個連接池,然後作爲參數 Redis,這樣就可以實現多個Redis實例共享一個連接池
使用連接池
import redis pool = redis.ConnectionPool(host='127.0.0.1',port=6609) r = redis.Redis(connection_pool=pool) r.set('name1','lili') print(r.get('name1'))
應用:頁面點擊數
需要對一系列頁面記錄點擊次數,如果使用關係數據庫來存儲點擊,可能存在大量的行級鎖爭用
(1)當redis服務器啓動時,可以從關係數據庫讀入點擊數的初始值
import redis r=redis.Redis(host='127.0.0.1',port=6609,db=0) r.set('visits:100',999)
(2)有人訪問頁面時
r.incr('visits:100')
(3)獲取頁面點擊數
r.get('visits:100')
Pipeline 是 StrictRedis 類的子類,支持在一個請求裏發送緩衝的多個命令。通過減少客戶端和服務器之間往來的數據包,可以大大提高命令組的性能
簡單使用
>>>import redis >>>r=redis.Redis(host='127.0.0.1',port=6609,db=0) >>> r.set('name', 'baby') >>> pipe = r.pipeline() >>> pipe.set('birthday', '2010') >>> pipe.get('name') >>> pipe.execute()
爲了方便使用,所有緩衝到 pipeline 的命令返回 pipeline 對象本身
調用可以連接起來
>>> pipe.set('name', 'baby').set('birthday', '2010').get('name').execute()
pipeline 也可以保證緩衝的命令組做爲一個原子操作
要使用命令緩衝,但禁止pipeline 的原子操作屬性,關掉 transaction
pipe = r.pipeline(transaction=False)
WATCH 命令提供了在開始事務前監視一個或多個鍵
這些鍵中的任何一個在執行事務前發生改變,整個事務就會被取消並拋出 WatchError 異常
import redis import time r=redis.Redis(host='127.0.0.1',port=6609,db=0) sellerid = 101 itemid = 101 price = 50 print(time.time()) def list_item(r,itemid,sellerid,price): inventory = "inventory:%s"%sellerid item = "%s.%s"%(itemid,sellerid) end = time.time()+5 pipe = r.pipeline() while time.time()<end: try: pipe.watch(inventory) if not pipe.sismember(inventory,itemid): pipe.unwatch() return None pipe.multi() pipe.zadd("market:",item,price) pipe.srem(inventory,itemid) pipe.execute() return True except redis.exceptions.WatchError: pass return False list_item(r,itemid,sellerid,price)
redis只會在數據已經被其他客戶端搶先修改了的情況下,通知執行了WATCH命令的客戶端,即--樂觀鎖
而關係型數據庫執行的加鎖操作爲悲觀鎖,這種方式下持有鎖的客戶端運行越慢,等待解鎖的客戶端被阻塞的時間越長
1 |
|
如果在watch後值被修改,在執行pipe.execute()的時候會報異常WatchError: Watched variable changed
redis只會在自己的事務執行失敗時重試
流水線:一次性發送多個命令,然後等待所有回覆出現。可以通過減少客戶端與redis服務器之間的網絡通信次數來提升redis在執行多個命令時的性能