当前位置:网站首页>【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()
边栏推荐
- Dump file generation, content, and analysis
- SAS data processing technology (1)
- 进程和线程
- How to determine how many bases a number is?
- SQL注入基础
- C language, operators of shift operators (> >, < <) explanation
- 报错:Client does not support authentication protocol requested by server; consider upgrading MySQL cli
- ROS Experimental Notes - Install QPEP and Intel-MKL
- ROS Experiment Notes - Validation of UZH-FPV Dataset
- Timers, synchronous and asynchronous APIs, file system modules, file streams
猜你喜欢
随机推荐
Ali P7 bask in January payroll: hard to fill the, really sweet...
Three-column layout implementation
工程师如何对待开源
ROS Experimental Notes - Install QPEP and Intel-MKL
如何利用原生JS实现回到顶部以及吸顶效果
深度学习 Transformer架构解析
[21天学习挑战赛——内核笔记](五)——devmem读写寄存器调试
部分准备金银行已经过时
Deep Learning Transformer Architecture Analysis
In 22 years, the salary of programmers nationwide in January was released, only to know that there are so many with annual salary of more than 400,000?
Why do programming languages have the concept of variable types?
How to recover deleted files from the recycle bin, two methods of recovering files from the recycle bin
关于科研学习中的几个问题:如何看论文?如何评价工作?如何找idea?
16. File upload
定时器,同步API和异步API,文件系统模块,文件流
CF1534F2-Falling Sand (Hard Version)
14. Thymeleaf
C语言%(%d,%c...)
【C语言】初识指针
基于Web的疫情隔离区订餐系统

![[C language] Detailed explanation of data storage](/img/3f/3799a3ba0f2642272e15bd7a3e511f.png)







