当前位置:网站首页>【redis】发布和订阅消息
【redis】发布和订阅消息
2022-08-10 23:50:00 【冰冷的希望】
1.说明
在Redis2版本之后支持发布订阅功能,发布者创建一个频道,并在上面发送消息,所有订阅该频道的客户端都能收到消息(不出意外的情况下,但实际不一定),发布订阅的好处是减少不必要的轮询,应用场景有即时聊天室、公众号订阅等。但Redis适合小型应用,如果是大型架构,相信还是会使用rabbitMQ或者kafka等更专业的MQ队列软件。
Redis-server内部会维护一个字典,键是频道名,值是一个存储订阅者的链表,每次发布消息都会遍历该链表进行推送。
2.订阅发布
我们打开一个redis终端,使用subscribe命令订阅频道,你不妨多打开几个终端同时订阅同一个频道,比如说我这里打开两个终端都订阅叫做chatChannel的频道
# 订阅格式:subscribe 频道名
127.0.0.1:6379> subscribe chatChannel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "chatChannel"
3) (integer) 1
再打开一个终端,使用publish命令发布消息,这样订阅该频道的终端都会打印结果
# 发布格式:publish 频道名 消息
127.0.0.1:6379> publish chatChannel "hello"
(integer) 2
结果如下图
每个客户端是可以同时订阅多个频道的,即subscribe参数指定多个频道,另外也可以使用psubscribe命令订阅多个频道(好像称为模式),支持正则表达式
# 同时订阅 频道1、频道2、频道3
subscribe 频道1 频道2 频道3
# 订阅所有以“chat”开头的频道
psubscribe chat*
如果想要取消订阅的话可以使用unsubscribe和punsubscribe命令,用法是命令后面加上频道或匹配模式
3.代码实现
订阅消息,比如说订阅3次之后取消订阅
from redis import Redis
r = Redis(host='localhost', port=6379, db=0)
p = r.pubsub() # 如果不想接收其他一些信息可以把参数ignore_subscribe_messages改为True
p.subscribe("testChannel") # 如果想要同时订阅多个频道,可以传入多个参数
# p.psubscribe("test*") # 模式匹配
i = 0
while True:
msg = p.get_message()
if msg:
print("来电了: ", msg)
i += 1
if i > 2:
break
# 取消订阅
p.unsubscribe()
# p.punsubscribe()
p.close()
r.close()
发布消息比较简单
from redis import Redis
r = Redis(host='localhost', port=6379, db=0)
r.publish('testChannel', 'hello everybody')
r.close()
边栏推荐
- 15. 拦截器-HandlerInterceptor
- YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5
- 阿里P7晒出1月工资单:狠补了这个,真香...
- SQL injection base
- “蔚来杯“2022牛客暑期多校训练营2 DGHJKL题解
- Excel English automatic translation into Chinese tutorial
- Timers, synchronous and asynchronous APIs, file system modules, file streams
- 7. yaml
- Design and implementation of flower online sales management system
- Lens filter---about day and night dual-pass filter
猜你喜欢
随机推荐
YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5
CF1427F-Boring Card Game【贪心】
Dump文件生成,内容,以及分析
Pagoda Test-Building PHP Online Mock Exam System
Cache knowledge summary
编程语言为什么有变量类型这个概念?
How to recover deleted files from the recycle bin, two methods of recovering files from the recycle bin
Lens filter---about day and night dual-pass filter
5. Lombok
SAS data processing technology (1)
SAS数据处理技术(一)
回收站的文件删了怎么恢复,回收站文件恢复的两种方法
ROS Experimental Notes - Install QPEP and Intel-MKL
如何判断一个数为多少进制?
[C language articles] Expression evaluation (implicit type conversion, arithmetic conversion)
分布式.性能优化
给肯德基打工的调料商,年赚两亿
从0开始设计JVM ,忘记名词跟上思路一次搞懂
C语言篇,操作符之 移位运算符(>>、<<)详解
地下管廊可视化管理系统搭建