Redis 的 SUBSCRIBE 命令可以让客户端订阅任意数量的频道, 每当有新信息发送到被订阅的频道时, 信息就会被发送给所有订阅指定频道的客户端。
作为例子, 下图展示了频道 channel1
, 以及订阅这个频道的三个客户端 —— client2
、 client5
和 client1
之间的关系:
当有新消息通过 PUBLISH 命令发送给频道 channel1
时, 这个消息就会被发送给订阅它的三个客户端:
代码实现:
定义一个类,实现了订阅发布的方法:
# -*- coding:utf-8 -*- import redis class SubscribePublished(object): ''' 用redis实现消息订阅与发布 ''' def __init__(self): # 初始化与redis的连接 self.connect = redis.Redis(host='127.0.0.1') # 消息发布的通道 self.put_channel = 'channel1' # 被订阅的通道 self.sub_channel = 'channel1' def publish(self, message): # 接受消息,并发送到指定通道 self.connect.publish(self.put_channel, message) return True def subscribe(self): pub = self.connect.pubsub() # 连接到指定通道 pub.subscribe(self.sub_channel) # 接受消息 pub.parse_response() return pub
publish
# -*- coding:utf-8 -*- from redis_test import SubscribePublished redis_obj = SubscribePublished() while True: # 模拟创建消息 message = input('please input message:') # 消息发往指定通道 redis_obj.publish(message)
Subscribe
# -*- coding:utf-8 -*- from redis_test import SubscribePublished redis_obj = SubscribePublished() # 客户端和要订阅的频道在 pubsub_channels 字典中关联起来 redis_sub = redis_obj.subscribe() while True: # parse_response 接受消息 message = redis_sub.parse_response() print(message)
先启动2个Subscribe,等待订阅消息:
python3 redis_sub.py
在启动一个Published发布消息:
python3 redis_pub.py
看结果:
发布消息:
订阅消息: