当前位置:网站首页>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构建的实时聊天系统的例子
边栏推荐
猜你喜欢

You'd better not take this kind of project!

QT writing IOT management platform 47 general database settings
C语言详解系列——函数的认识(4)函数的声明与定义,简单练习题

Hack the box - Introduction to networking module detailed Chinese tutorial

DOM event flow event bubble event capture event delegate

Basic methods of realizing licensing function in C language

Yolov3 preparatory work

Use playbook in ansible

Mongondb API usage

Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images
随机推荐
The first positive number missing in question 41 of C language. Two methods, preprocessing, fast sorting and in situ hashing
Hack the box - Web requests module detailed Chinese tutorial
Debugging sharp weapon! A lightweight log library log.c
jupyter notebook快捷键
Hack The Box - Web Requests Module详细讲解中文教程
Hack the box - Introduction to networking module detailed Chinese tutorial
Getaverse,走向Web3的远方桥梁
Do you really understand fiddler, a necessary tool for testing?
no networks found in /etc/cni/net.d
MongoDB 常用命令
Development to testing: a six-year road to automation from scratch
Three implementation methods of thread and the usage of handler
C language function
SSH Remote Management
A trick to teach you to easily understand Potter's map
C language explanation series -- understanding of functions (3) formal parameters, arguments, nested calls and chain access
nn.Moudle模块-创建神经网络结构需要注意的细节
动态内存管理及柔性数组
LNMP架构
DOM操作--操作节点