快取資料庫-redis(訂閱發布)

來源:互聯網
上載者:User

標籤:scribe   訊息   開啟   src   init   ima   imp   img   run   

一:Redis 發布訂閱

Redis 發布訂閱(pub/sub)是一種訊息通訊模式:寄件者(pub)發送訊息,訂閱者(sub)接收訊息。

Redis 用戶端可以訂閱任意數量的頻道。

展示了頻道 channel1 , 以及訂閱這個頻道的三個用戶端 —— client2 、 client5 和 client1 之間的關係:

當有新訊息通過 PUBLISH 命令發送給頻道 channel1 時, 這個訊息就會被發送給訂閱它的三個用戶端:

 

二:樣本
# -*- coding:utf-8 -*-__author__ = ‘shisanjun‘import redisclass RedisHelper(object):    def __init__(self):        self.__conn=redis.Redis(host="192.168.0.121")        self.chan_sub="fm104.5"        self.chan_pub="fm104.5"    def public(self,msg):        self.__conn.publish(self.chan_pub,msg)        return True    def subscribe(self):        pub=self.__conn.pubsub()#相當於開啟收音機        pub.subscribe(self.chan_sub)#調頻道        pub.parse_response()#準備接受,下次調用才開始接受        return pub

 

訂閱

# -*- coding:utf-8 -*-__author__ = ‘shisanjun‘from redishelp import RedisHelperobj=RedisHelper()redis_sub=obj.subscribe()while True:    msg=redis_sub.parse_response()    print(msg)

發布

# -*- coding:utf-8 -*-__author__ = ‘shisanjun‘from redishelp import RedisHelperobj=RedisHelper()obj.public("hello")

 

快取資料庫-redis(訂閱發布)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.