python 實現redis訂閱發布功能,pythonredis

來源:互聯網
上載者:User

python 實現redis訂閱發布功能,pythonredis

redis是一個key-value儲存系統。和Memcached類似,它支援儲存的value類型相對更多,包括string(字串)、list(鏈表)、set(集合)、zset(sorted set --有序集合)和hash(雜湊類型)。也能實現訂閱發布系統,我們來看看怎樣用redis和python結合起來進行訂閱發布的,

import  redisclass RedisSubscri():    def __init__(self,host):        self.coon=redis.Redis(host="127.0.0.1")    def publish(self,message,channel):#發布        self.coon.publish(channel,message)    def subscribe(self,channel):#訂閱        pub=self.coon.pubsub()        pub.subscribe(channel)        pub.parse_response()        return  pub    def unsubsceribe(self,channel):#取消訂閱        self.coon.pubsub().unsubscribe(channel)

 核心的代碼就是上面的 簡單封裝後就可以使用。

發布端redisd=RedisSubscri(host='127.0.0.1')while True:n=input("請輸入你要發布的頻道:")m=input("請輸入你要發布的訊息:")redisd.publish(m,n)
訂閱端from  dingyue import RedisSubscriif __name__=="__main__":    resad = RedisSubscri(host='127.0.0.1')    meaaag = resad.subscribe('1')    while True:        print('監聽開始')        meaaage=meaaag.parse_response()        print(meaaage[2].decode('utf-8'))        if meaaage[2].decode('utf-8')=='1':            m=meaaag.unsubscribe('fm9.01')            print(m)            print('取消訂閱成功')            break

那麼我們來運行下,上述的代碼,看是否能夠實現登入訂閱功能,並且實現退訂功能。

發布端:

訂閱端

 

我們在上面的代碼中定義了,當接受訊息為1的時候,我們就取消訂閱,

取消訂閱後就無法訂閱系統的訊息了,所以輸出來是None。

這樣就利用python 和redis實現了訂閱發布的功能,其實在很多地方都可以用到redis的,深入研究在後續的文章中會介紹。

 

一點一滴,學習python, 點點滴滴,記錄python之路。

人生苦短我用python。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.