redis __实现发布订阅

第一步:创建订阅发布类

## 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}
发布了128 篇原创文章 · 获赞 0 · 访问量 2519

猜你喜欢

转载自blog.csdn.net/qq_41134008/article/details/105068980