作者:sdfqw4543gf | 来源:互联网 | 2023-12-14 15:04
本文介绍了使用Python实现Redis订阅发布功能的方法,包括创建RedisHelper类、发布消息和订阅消息的操作。通过该功能,可以实现消息的发布和订阅,并在程序中进行相应的处理。
#7512
import redis
class RedisHelper:
def __init__(self):
self.__cOnn= redis.Redis(host='127.0.0.1')
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
monitor
1 from monitor import RedisHelper
2
3 obj = RedisHelper()
4 while True:
5 msg = input(">>:")
6 obj.public(msg)
发布者
1 #7512
2 from monitor import RedisHelper
3
4 obj = RedisHelper()
5 redis_sub = obj.subscribe()
6
7 while True:
8 msg = redis_sub.parse_response()
9 print(msg)
订阅者