python redis 實現訂閱發布


help 類:

import redis

class RedisHelper:
    def __init__(self):
        self.__conn = redis.Redis(host='192.168.117.138')
        self.chan_sub = 'test'
        self.chan_pub= 'test'

#發送消息
    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

 

訂閱者:

'''訂閱方'''

from  redishelper import RedisHelper

obj = RedisHelper()
redis_sub = obj.subscribe()

while True:
    msg = redis_sub.parse_response()
    print('接收:',msg)

 

 

發布者:

'''
發布者
'''

from  redishelper import RedisHelper

obj = RedisHelper()
obj.public('how are you?')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM