当前位置:网站首页>Redis发布订阅
Redis发布订阅
2022-07-26 05:34:00 【生命不止、战斗不息】
是什么
Redis发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发布消息,订阅者(sub)接收消息。
Redis客户端可以订阅任意数量的频道
订阅/发布消息图:

下图展示了频道channel1,以及订阅这个频道的三个客户端----client2,client5和client1之间的关系:

当有新消息通过PUBLISH命令发送给频道channel1时,这个消息就会被发送给订阅它的三个客户端:

命令
这些评论被广泛用于构建即时通信应用,比如网络聊天室(chatroom)和实时广播,实时提醒等

测试
以下实例演示了发布订阅是如何工作的,在我们实例中我们创建额订阅频道名为redischat;
127.0.0.1:6379> subscribe redischat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redischat"
3) (integer) 1
现在,我们先重新开启一个reids客户端,然后在同一个频道redischat发布两次消息,订阅者就能接收到消息
127.0.0.1:6379> publish redischat hello,wyt
(integer) 1
127.0.0.1:6379> publish redischat hello,redis
(integer) 1
# 订阅者的客户端会显示如下消息1) "message"
2) "redischat"
3) "hello,wyt"
1) "message"
2) "redischat"
3) "hello,redis"
原理
Redis是使用C实现的,通过分析Redis源码里的pubsub.c文件,了解发布和订阅机制的底层实现,籍此加深对Redis的理解
Redis通过PUBSLISH、SUBSCRIBE和PSUBSCRIBE等命令实现发布和订阅功能
通过SUBSCRIBE命令订阅某频道后,reids-server里维护了一个字典,字典的键就是一个个chnnel,而字典的值则是一个链表,链表中保存了所有订阅这个channel的客户端,SUBSCRIBE命令的关键,就是将客户端添加到给定channel的订阅链表中。
通过PUBLISH命令向订阅者发送消息,redis-server会使用给定的频道作为键,在它所维护的channel字典中查找记录了订阅这个频道的所有客户端的链表,遍历这个链表,将消息发布给所有订阅者
Pub/Sub从字面上理解就是发布(Publish)与订阅(Subscribe),在Redis中,你可以设定对某一个key值进行消息发布及消息订阅,当一个key值上进行了消息发布后,所有订阅它的客户端都会收到相应的消息,这一功能最明显的用法就是用作实时消息系统,比如普通的即时聊天,群聊等功能
使用场景
Pub/Sub构建实时消息系统
Redis的Pub/Sub系统可以构建实时的消息系统
比如很多用Pub/Sub构建的实时聊天系统的例子
边栏推荐
猜你喜欢

Debugging sharp weapon! A lightweight log library log.c

Go exceed API source code reading (VI) -- deletesheet (sheet string)

YOLOV3预备工作

Getaverse, a distant bridge to Web3
C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises

Polymer physics test question bank

ALV program collection

Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output

Knowledge points of Polymer Physics

一招教你轻松看懂波特图
随机推荐
Getaverse, a distant bridge to Web3
Bash shortcut key to improve command line efficiency [Full Version]
Nn.moudle module - details of creating neural network structure
C language function
STL常用模板库
一招教你轻松看懂波特图
Development to testing: a six-year road to automation from scratch
LNMP architecture
TZC 1283: simple sort Bubble Sort
Yolov3 preparatory work
Basic methods of realizing licensing function in C language
[STM32 series summary] blogger's way to quickly advance STM32 in actual combat (continuous update)
Three implementation methods of thread and the usage of handler
LAMP架构
三本毕业,三年嵌入式软件的心路历程
Attack and defense world -- easy_ web
《MongoDB入门教程》第08篇 比较运算符
How to name the project version number? Looks like cow b
Hack The Box - Web Requests Module详细讲解中文教程
OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation