python学习之-- redis模块管道/订阅发布
redis 模塊操作剩余其他常用操作
delete(*names):刪除任意的數(shù)據(jù)類型
exists(name):檢測redis的name是否存在
keys(pattern='*'):根據(jù)模型獲取redis的name
keys * 匹配數(shù)據(jù)庫中所有Key
keys h?llo:匹配hello,hallo,hxllo等
expire(name,time):為redis的某個(gè)name設(shè)置超時(shí)時(shí)間
rename(src,dst):對redis的name重命名
move(name,db):將redis的某個(gè)值移動(dòng)到指定的db下
randomkey():隨機(jī)獲取一個(gè)redis的name(不刪除)
type(name):獲取name對應(yīng)的類型
scan(cursor=0, match=None, count=None)
scan_iter(match=None, count=None)
# 同字符串操作,用于增量迭代獲取key
管道
redis-py默認(rèn)在執(zhí)行每次請求都會(huì)創(chuàng)建(連接池申請鏈接)和斷開(歸還連接池)一次連接操作,如果想要在一次請求中指定多個(gè)命令,則可以使用pipline實(shí)現(xiàn)一次請求執(zhí)行多個(gè)命令,并且默認(rèn)情況下一次pipline是原子性操作。
實(shí)例
1 import redis 2 pool = redis.Connection(host='10.10.2.12',port=6379,db=5) # 可以設(shè)置存儲(chǔ)使用的db,默認(rèn)是0 3 r = redis.Redis(connection_pool=pool) 4 pipe = r.pipeline(transaction=True) # 啟動(dòng)管道 5 pipe.set('name','jack') # 寫數(shù)據(jù) 6 pipe.set('age',20) 7 pipe.execute() # 啟動(dòng)執(zhí)行 View Code訂閱/發(fā)布舉例:
主程序類:
1 import redis 2 class RedisHelper(object): 3 def __init__(self): 4 self.__conn = redis.Redis(host='10.10.2.14',port=6379) 5 self.chan_sub = 'fm104.5' 6 self.chan_pub = 'fm104.5' 7 def public(self,msg): # 發(fā)布 8 self.__conn.publish(self.chan_pub,msg) # 向chan_pub的頻道發(fā)Msg消息,publish是redis的方法 9 return True 10 def subscribe(self): # 訂閱 11 pub = self.__conn.pubsub() # 開始訂閱==打開收音機(jī) 12 pub.subscribe(self.chan_sub) # 選擇頻道為fm104.5 13 pub.parse_response() # 準(zhǔn)備接收,啟動(dòng)程序里再次調(diào)用parse_response才進(jìn)入接收 14 return pub View Code訂閱:
1 from redis_helper import RedisHelper 2 obj = RedisHelper() 3 redis_sub = obj.subscribe() # 進(jìn)入準(zhǔn)備接收狀態(tài) 4 while True: 5 msg = redis_sub.parse_response() # 這里再次調(diào)用parse_response進(jìn)入接收狀態(tài) 6 print(msg) View Code發(fā)布:
1 from redis_helper import RedisHelper 2 obj = RedisHelper() 3 obj.public('hello') # 發(fā)送消息hello View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/zy6103/p/7084071.html
與50位技術(shù)專家面對面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python学习之-- redis模块管道/订阅发布的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浅读《视觉SLAM十四讲:从理论到实践》
- 下一篇: 浅谈python的对象的三大特性之封装