安裝包
- 到中文官網(wǎng)查找客戶端代碼
- 聯(lián)網(wǎng)安裝
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ù)類型的不同包个,調(diào)用相應(yīng)的方法私股,完成讀寫
- 更多方法同前面學(xué)的命令
r.set('name','hello')
r.get('name')
- 方式二:pipeline
- 緩沖多條命令摹察,然后一次性執(zhí)行,減少服務(wù)器-客戶端之間TCP數(shù)據(jù)庫(kù)包倡鲸,從而提高效率
pipe = r.pipeline()
pipe.set('name', 'world')
pipe.get('name')
pipe.execute()
封裝
- 連接redis服務(wù)器部分是一致的
- 這里將string類型的讀寫進(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)
代碼奉上:
#coding=utf8
from redis import *
r = StrictRedis(host="localhost",port=6379)
#寫
# pipe = r.pipeline()
# pipe.set("py10","hello")
# pipe.set("py11","world")
# pipe.execute()
# 讀
# temp = r.get("py11")
# print(temp)
# 封裝
class redisHelper():
def __init__(self,host,port):
self.__redis = StrictRedis(host,port)
def set(self,key,value):
self.__redis.set(key,value)
def get(self,key):
return self.__redis.get(key)