第3章 小功能大用处-发布订阅

Redis提供了基于"发布/订阅"模式的消息机制,此种模式下,消息发布者和订阅者不进行直接通信,发布者客户端向指定的频道(channel)发布消息,订阅该频道的每个客户端都可以收到该消息。

命令 :Redis主要提供了发布消息、订阅频道、取消订阅以及按照模式订阅和取消订阅等命令。
1.发布消息 :publish channel message

下面操作会向channel:sports频道发布一条消息"Tim won the

championship",返回结果为订阅者个数,如果没有订阅,返回结果为0:

powershell 复制代码
127.0.0.1:6379> publish channel:sports "Tim won the championship"
(integer) 0

2.订阅消息 :subscribe channel channel ...

订阅者可以订阅一个或多个频道,下面操作为当前客户端订阅了channel:sports频道:

powershell 复制代码
127.0.0.1:6379> subscribe channel:sports
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel:sports"
3) (integer) 1

有关订阅命令有两点需要注意:

  • 客户端在执行订阅命令之后进入了订阅状态,只能接收subscribe、psubscribe、unsubscribe、punsubscribe的四个命令。
  • 新开启的订阅客户端,无法收到该频道之前的消息,因为Redis不会对
    发布的消息进行持久化。
    如果有多个客户端同时订阅了channel:sports,整个过程如下图所示。

    开发提示 :和很多专业的消息队列系统(例如Kafka、RocketMQ)相比,Redis的发布订阅略显粗糙,例如无法实现消息堆积和回溯。但胜在足够简单,如果当前场景可以容忍的这些缺点,也不失为一个不错的选择。
    3.取消订阅
    unsubscribe channel \[channel ...]
    客户端可以通过unsubscribe命令取消对指定频道的订阅,取消成功后,不会再收到该频道的发布消息:
powershell 复制代码
127.0.0.1:6379> unsubscribe channel:sports
1) "unsubscribe"
2) "channel:sports"
3) (integer) 0

4.按照模式订阅和取消订阅

psubscribe pattern pattern...

punsubscribe pattern \[pattern ...]

除了subcribe和unsubscribe命令,Redis命令还支持glob风格的订阅命令psubscribe和取消订阅命令punsubscribe,例如下面操作订阅以it开头的所有频道:

powershell 复制代码
127.0.0.1:6379> psubscribe it*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "it*"
3) (integer) 1

5.查询订阅

(1)查看活跃的频道

pubsub channels pattern

所谓活跃的频道是指当前频道至少有一个订阅者,其中pattern是可以指定具体的模式:

powershell 复制代码
127.0.0.1:6379> pubsub channels
1) "channel:sports"
2) "channel:it"
3) "channel:travel"
127.0.0.1:6379> pubsub channels channel:*r*
1) "channel:sports"
2) "channel:travel"

(2)查看频道订阅数

pubsub numsub channel ...

当前channel:sports频道的订阅数为2:

powershell 复制代码
127.0.0.1:6379> pubsub numsub channel:sports
1) "channel:sports"
2) (integer) 2

(3)查看模式订阅数

pubsub numpat

当前只有一个客户端通过模式来订阅:

powershell 复制代码
127.0.0.1:6379> pubsub numpat
(integer) 1
相关推荐
hweiyu0010 小时前
Redis命令:LMOVE
redis·缓存
bug菌11 小时前
一个周末就想把短链服务推到 10 万 QPS,真能靠加 Redis 做到吗?
java·redis·go
程序员Sunday13 小时前
Redis 缓存穿透、击穿、雪崩怎么区分?从回源压力找原因
数据库·redis·缓存
guo_wen_qiang13 小时前
redis实现秒杀功能-超卖&库存遗留问题的解决
数据库·redis·缓存
逐流人13 小时前
Redis内存数据库:从数据类型到集群部署
linux·运维·数据库·redis·缓存·云计算
.Bryce.16 小时前
三协议合一实战:用MCP+A2A+ANP搭建一个智能研究助手
网络·redis·agent·codex·mcp·a2a·anp
大侠归来16 小时前
Redis Cluster 的 16384 个槽(Slot)是什么?
数据库·redis·缓存
杨运交17 小时前
[079][消息模块]基于 Redis Stream 的高可靠消息队列实现——Spring Data Redis 实战解析
数据库·redis·spring
xixingzhe217 小时前
秒杀库存三种缓存实现方案
数据库·redis·缓存
思考着亮19 小时前
1.Redis 基础知识
redis