第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
相关推荐
小小工匠13 小时前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
taocarts_bidfans17 小时前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
炘爚19 小时前
Linux——Redis
数据库·redis·缓存
csjane107920 小时前
Redisson 限流原理
java·redis
ThanksGive20 小时前
Go 服务里的 Redis 锁惊群问题:一次本地合流优化实践
redis
小挪号底迪滴20 小时前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存
闪电悠米21 小时前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Devin~Y1 天前
大厂 Java 面试实录:从音视频内容社区到 AI RAG 的全链路技术设计
java·spring boot·redis·spring cloud·微服务·kafka·音视频
小小工匠1 天前
Redis - 主从集群脑裂:数据丢失的隐藏杀手
数据库·redis