安裝redis-py
sudo pip2 install redis
牛刀小試
redis連接實例是線程安全的,可以直接將redis
連接實例設置為一個全局變量直接使用。如果需要另一個Redis
實例(or Redis數據庫),需要重新創建redis
連接實例來獲取一個新的連接。有余這個原因,python的redis接口沒有實現select
命令。
首先,導入相應的包
import redis
接着,創建連接redis實例
rcon = redis.Redis(host="localhost",port=6379,db=0)
或
rcon = redis.StrictRedis(host="localhost",port=6379,db=0)
這兩者之間的差別可以瀏覽這個問題
redis-py exposes two client classes that implement these commands
TheStrictRedis
class attempts to adhere to the official command syntax.
and
In addition to the changes above, theRedis
class, a subclass ofStrictRedis
,
overrides several other commands to provide backwards compatibility with older
versions of redis-py
Do you need backwards compatibility? UseRedis
. Don't care? UseStrictRedis
.
簡單來說就是Redis
是StrictRedis
的子類,用來兼容之前版本的Redis
,如果你沒有需要兼容的,就用StrictRedis
下面就來嘗試一些redis-cli
中使用的命令吧
>>> rcon.set('name','Tacey Wong')
True
>>> rcon.get('name')
'Tacey Wong'
>>> rcon['name']
'Tacey Wong'
>>> rcon.keys()
['name']
>>> rcon.dbsize() #當前數據庫中數據條數
1L
>>> rcon.delete('name')
1
>>> rcon.save() #將數據寫回磁盤(保存時阻塞)
True
>>> rcon.get('name');
>>> rcon.flushdb() #清控rcon實例所選db中的數據
>>> rcon.flushall() #清空rcon實例中的所有數據(所有db)
Python中使用Redis的管道(pipeline)
管道(pipeline)是redis在提供單個請求中緩沖多條服務器命令的基類子類。通過減少服務器-客戶端之間反復的TCP數據庫包,從而大大提高了執行批量命令的功能。
創建一個管道
_pipe = rcon.pipeline()
准備多個命令
_pipe.set('hello','redis')
_pipe.sadd('faz','baz')
_pipe.incr('num')
一次性執行上邊的三個命令
>>> _pipe.execute()
[True, 1, 1]
測試讀取上邊存入的一條數據
>>> rcon.get('hello')
'redis'
管道的命令可以寫在一起,如上邊的命令可以寫成下面的形式:
>>> p.set('hello','redis').sadd('faz','baz').incr('num').execute()
1
默認的情況下,管道里執行的命令可以保證執行的原子性,將transaction
設置為False
:_pipe = rcon.pipeline(transaction=False)
可以禁用這一特性。
后續
參考Redis
的Redis-cli
命令