標籤:else exe get red except watcher port scribe inpu
python和redis之間的互動一. redis模組
安裝模組:
pip3 install redis
串連方式:
r = redis.Redis(host=‘localhost‘,port=6379)
串連池:為了節約資源,減少多次串連帶來的消耗。
pool=redis.ConnectionPool(host=‘localhost‘,port=6379,decode_responses=True)
二.redis操作
常規操作:
import redisr = redis.Redis(host=‘localhost‘,port=6379)r.set(‘foo‘,‘bar‘)print(r.get(‘foo‘))
串連池:
import redispool = redis.ConnectionPool(host=‘localhost‘,port=6379,decode_responses=True)# 預設設定的值和取得的值都是bytes類型,如果想改為str類型,可以添加decode_responses=Truer1 = redis.Redis(connection_pool=pool)r2 = redis.Redis(connection_pool=pool)r1.set(‘name‘,‘jack‘)print(r1.get(‘name‘))r2.set(‘age‘,18)print(r2.get(‘age‘))print(r1.client_list())print(r2.client_list())
管道:
import redis,timer = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)pipe = r.pipeline(transaction=True)pipe.set(‘name1‘,‘Alin‘)pipe.set(‘name2‘,‘Lnda‘)pipe.set(‘name3‘,‘Tony‘)time.sleep(5) pipe.execute()print(r.mget(‘name1‘,‘name2‘,‘name3‘))
事務:python可以使用管道來代替事務
import redis,timeimport redis.exceptionsr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)pipe = r.pipeline()print(r.get(‘name1‘))try: pipe.multi() pipe.set(‘age1‘,22) pipe.set(‘age2‘,23) pipe.set(‘age3‘,24) time.sleep(5) pipe.execute() print(r.mget(‘age1‘,‘age2‘,‘age3‘))except redis.exceptions.WatchError as e: print(‘Error‘)
訂閱和發布:
發布方:
import redisr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)while True: msg = input(‘echo>>:‘) if len(msg) == 0: continue elif msg == ‘quit‘: r.publish(‘cctv1‘,msg) break else: r.publish(‘cctv1‘,msg)
訂閱者:
import redisr = redis.Redis(host=‘localhost‘,port=6379,decode_responses=True)chan = r.pubsub() #返回一個發布訂閱對象msg_reciver = chan.subscribe(‘cctv1‘) #訂閱msg = chan.parse_response() # 返回一個確認print(msg)print(‘訂閱成功,開始接收...‘)while True: msg = chan.parse_response() #接收訊息 if msg[2] == ‘quit‘: #格式:類型,頻道,訊息 break else: print(‘>>:‘, msg[2])
python和redis之間的互動