当前位置:网站首页>【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()
边栏推荐
猜你喜欢
7. yaml
图片懒加载(纯手写)
3. 容器功能
How to recover deleted files from the recycle bin, two methods of recovering files from the recycle bin
2. Dependency management and automatic configuration
Special class and type conversion
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
给肯德基打工的调料商,年赚两亿
PMP每日一练 | 考试不迷路-8.10(包含敏捷+多选)
翻译软件哪个准确度高【免费】
随机推荐
15. 拦截器-HandlerInterceptor
Cache knowledge summary
Part of the reserve bank is out of date
[C language articles] Expression evaluation (implicit type conversion, arithmetic conversion)
【C语言篇】表达式求值(隐式类型转换,算术转换)
Excel English automatic translation into Chinese tutorial
[C language] Detailed explanation of data storage
[Excel knowledge and skills] Convert "false" date to "true" date format
如何便捷获取参考文献的引用格式?
[Excel knowledge and skills] Convert text numbers to numeric format
只会懒汉式和饿汉式 你还不懂单例模式!
从0开始设计JVM ,忘记名词跟上思路一次搞懂
好用的翻译插件-一键自动翻译插件软件
阿里P7晒出1月工资单:狠补了这个,真香...
Is there a way out in the testing industry if it is purely business testing?
12. Handling JSON
ROS Experimental Notes - Install QPEP and Intel-MKL
HGAME 2022 Final Pokemon v2 writeup
IEEE的论文哪里可以下载?
Software protection scenario of NOR FLASH flash memory chip ID application