Redis使用總結(2):Python接口


安裝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
The StrictRedis class attempts to adhere to the official command syntax.
and
In addition to the changes above, the Redis class, a subclass of StrictRedis,
overrides several other commands to provide backwards compatibility with older
versions of redis-py
Do you need backwards compatibility? Use Redis. Don't care? Use StrictRedis.

簡單來說就是RedisStrictRedis的子類,用來兼容之前版本的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)可以禁用這一特性。

后續
參考RedisRedis-cli命令


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM