原理
Redis订阅模式为发布者发布消息,订阅者轮询获取消息的模式,一般先启动订阅者,然后再启动发布者。
订阅者代码演示
import redis # 引入库
r = redis.Redis(host='1.1.1.1',port=6379) # 建立连接
channel = 'test_channel1' # 定义频道名
sub_obj = r.pubsub() # 创建订阅对象
sub_obj.subscribe(channel) # 订阅到指定的频道上
sub_obj.parse_response() # 等待消息
while True: # 无限循环
msg = sub_obj.parse_response() # 得到消息内容
print(msg)
发布者代码演示
import redis
r = redis.Redis(host='10.20.17.13',port=6379) # 建立连接
channel = 'test_channel1' # 频道名,要和订阅代码一致
r.publish(channel, "msg1") # 发送消息
r.publish(channel, "msg2")
与队列的区别
在取消息消费这一点,订阅模式和队列很相似,但是它们之间还是有区别的。
- 队列中的消息只能被一个消费者取走(redis列表数据类型的属性),而订阅模式消息可以被多个向消费者获取到。
- 消息队列中的消息如果没有被消费的话,那么它可以一直存在队列中,而订阅模式的消息如果没有被消费的话就会消失掉。
订阅多个频道代码演示
import redis # 引入redis模块
import time, _thread # 引入时间和线程模块
def thread_entry(sub_obj): # 线程入口函数
for i in range(10): # 循环10次
msg = sub_obj.parse_response() # 得到消息
print("Received Msg: %s" % msg) # 打印消息内容
r = redis.Redis(host='127.0.0.1',port=6379) # 连接Redis服务器
channel1 = 'test_channel1' # 两个频道
channel2 = 'test_channel2'
sub_obj = r.pubsub()
sub_obj.subscribe(channel1, channel2)
sub_obj.parse_response()
sub_obj.parse_response()
_thread.start_new_thread(thread_entry, (sub_obj,)) # 启动线程
time.sleep(1)
r.publish(channel1, "msg1") # 在第一个频道发送消息
time.sleep(1)
r.publish(channel2, "msg2") # 在第二个频道发送消息
time.sleep(1)
频道使用通配符
如果使用 psubscribe() 来订阅某个频道,可以是使用通配符“”,表示符合该模式的所有频道。例如可以用“test_channel”来表示所有以 test_channel 开头的频道,这样发送给 test_channel1、test_channel2 等频道的消息它都可以收到。