import redis try: r=redis.StrictRedis(host='localhost',port=6379) except Exception,e: print e.message
//方式一:根據數據類型的不同,調用相應的方法,完成讀寫 r.set('name','hello') r.get('name') //方式二:pipline //緩沖多條命令,然后一次性執行,減少服務器-客戶端之間TCP數據庫包,從而提高效率 pipe = r.pipeline() pipe.set('name', 'world') pipe.get('name') pipe.execute()
封裝
- 連接redis服務器部分是一致的
- 這里將string類型的讀寫進行封裝
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)
示例:用戶登錄
- 業務過程如下:
- 輸入用戶名、密碼
- 密碼加密
- 判斷redis中是否記錄了用戶名,如果有則成功
- 如果redis中沒有用戶名,則到mysql中查詢
- 從mysql中查詢成功后,將用戶名記錄到redis中
#encoding=utf-8 from t2 import RedisHelper from t3 import MysqlHelper import hashlib name=raw_input("請輸入用戶名:") pwd=raw_input("請輸入密碼:") sha1=hashlib.sha1() sha1.update(pwd) pwd1=sha1.hexdigest() try: redis=RedisHelper() if redis.get('uname')==name: print 'ok' else: mysql=MysqlHelper('localhost',3306,'test1','root','mysql') upwd=mysql.get_one('select upwd from userinfos where uname=%s',[name]) if upwd==None: print '用戶名錯誤' elif upwd[0]==pwd1: redis.set('uname', name) print '登錄成功' else: print "密碼錯誤" except Exception,e: print e.message