redis __实现发布订阅

本文详细介绍了如何使用Redis实现发布订阅功能,包括创建订阅发布类、发布消息以及订阅消息的三个步骤。
摘要由CSDN通过智能技术生成

第一步:创建订阅发布类

## xx.py
import redis
class RedisHelper:
	def __init__(self):
		self.__conn = redis.Redis(host='localhost')
		self.chan_sub = 'channl'  # 定义频道
	def public(self,msg):
		self.__conn.publish(self.chan_sub,msg) # 在指定的频道上发布消息,返回订阅者的数量
		return True
	def subscribe(self):
		pub = self.__conn.pubsub()
		pub.subscribe(self.chan_sub)
		return pub

第二步:发布消息

## yy.py
obj = RedisHelper()
for i in range(5):
	obj.public('hello world','------',i)

第三步:订阅消息

# xx.py
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
	msg = redis_sub.listen()  # listen()函数分装了parse_response()函数
	for i in msg:
		if i['type']=='message':
			print(str(i['channel'],encoding='utf-8')+ ":" + str(i["data"], encoding="utf-8"))
		elif i['type'] =='subscrube':
			print(str(i["chennel"], encoding="utf-8"))

	print(i)  #---{'type': 'subscribe', 'pattern': None, 'channel': b'orders', 'data': 1}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值