第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
相关推荐
Keanu-1 天前
Redis 主从复制及哨兵模式配置
服务器·数据库·redis
初次攀爬者1 天前
Redis与数据库的数据一致性方案解析
数据库·redis·分布式
EAIReport1 天前
MongoDB、Redis、HBase 三大NoSQL数据库:核心区别与选型指南
redis·mongodb·hbase
fengxin_rou1 天前
一文读懂 Redis 集群:从哈希槽到透明访问
java·数据库·redis·算法·spring·缓存
咖啡の猫1 天前
Redis 通用命令
数据库·redis·bootstrap
fengxin_rou1 天前
黑马点评实战篇|第五篇:分布式锁-redission
java·数据库·redis·后端·缓存
J2虾虾1 天前
给Redis增加密码
数据库·redis·缓存
Fox爱分享1 天前
阿里二面:如何保证 Redis 和 MySQL 的数据一致性?还在背“延时双删”的Sleep玄学?教你高性能 + 高可靠的方案
redis·后端·面试
ん贤1 天前
为什么我没有直接上 MQ,而是自研了一套轻量事件驱动引擎
redis·mq·事件驱动·引擎
筱顾大牛1 天前
点评项目---分布式锁
java·redis·分布式·缓存·idea