安裝包
sudo pip install redis
unzip redis-py-master.zip
cd redis-py-master
sudo python setup.py install
交互代碼
import redis
try:
r=redis.StrictRedis(host='localhost',port=6379)
except Exception,e:
print e.message
- 方式一:根據(jù)數(shù)據(jù)類(lèi)型的不同,調(diào)用相應(yīng)的方法连舍,完成讀寫(xiě)
- 更多方法同前面學(xué)的命令
r.set('name','hello')
r.get('name')
- 方式二:pipline
- 緩沖多條命令没陡,然后一次性執(zhí)行,減少服務(wù)器-客戶端之間TCP數(shù)據(jù)庫(kù)包索赏,從而提高效率
pipe = r.pipeline()
pipe.set('name', 'world')
pipe.get('name')
pipe.execute()
封裝
- 連接redis服務(wù)器部分是一致的
- 這里將string類(lèi)型的讀寫(xiě)進(jìn)行封裝
import redis
class RedisHelper():
def __init__(self,host='localhost',port=6379):
self.__redis = redis.StrictRedis(host, port)
def get(self,key):
if self.__redis.exists(key):
return self.__redis.get(key)
else:
return ""
def set(self,key,value):
self.__redis.set(key,value)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者