Redis 发布订阅

概述

https://redis.io/docs/manual/pubsub/ (opens in a new tab)

发布订阅时一种消息通信模式:发送者(PUSLISH)发送消息,订阅者(SUBSCRIBE)接收消息,可以实现进程间的消息传递。

Redis 可以实现消息中间件 MQ 的功能,通过发布订阅实现消息的引导和分流(不推荐使用该功能)。

作用

例如:Redis 客户端可以订阅任意数量的频道,类似我们微信关注多个公共号;当有新消息通过 PUBLISH 命令发送给频道,频道推送到各个客户端。

发布/订阅其实是一个轻量的队列,只不过数据不会被持久化,一般用来处理实时性较高的异步消息

常用命令

  • SUBSCRIBE channel [channel ...]

    订阅给定的一个或多个频道的信息

    推荐先执行订阅后再发布。订阅成功之前发布的消息时收不到的

    订阅的客户端每次可以收到一个 3 个参数的消息

    • 消息的种类
    • 始发的频道名称
    • 实际的消息内容
  • SUBSCRIBE channel message

    发布消息到指定的频道

  • PUBLISH pattern [pattern ...]

    按照模式批量订阅,订阅一个或多个符合给定模式(支持 * ?等符号)的频道

  • PUBLISH subcommand [argument [argument ...]]

    查看订阅与发布系统状态

    PUBSUB CHANNELS 由活跃频道组成的列表

    PUBSUB NUMSUB [channel [channel ...]] 某个频道有几个订阅者

    PUBSUB NUMPA 只统计使用 PSUBSCRIBE 命令执行的,返回客户端订阅的唯一模式的数量

  • UNSUBSCRIBE [channel [channel ...]]

    取消订阅

  • PUNSUBSCRIBE [pattern [pattern ...]]

    退订所有给定模式的频道

示例

环境介绍

开启 3 个客户端,演示客户端 A、B 订阅消息,客户端 C 发布消息

127.0.0.1:6379> SUBSCRIBE c1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
1) "message"
2) "c1"
3) "hello,c1"
127.0.0.1:6379> SUBSCRIBE c1 c2
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
1) "subscribe"
2) "c2"
3) (integer) 2
1) "message"
2) "c1"
3) "hello,c1"
127.0.0.1:6379> SUBSCRIBE c1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
^C(49.83s)
127.0.0.1:6379> PUBLISH c1 hello,c1
(integer) 2
127.0.0.1:6379> PSUBSCRIBE c* a?
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "c*"
3) (integer) 1
1) "psubscribe"
2) "a?"
3) (integer) 2
^C(35.73s)
127.0.0.1:6379> PUBSUB NUMPAT
(integer) 0
127.0.0.1:6379> PUBSUB CHANNELS
1) "c2"
2) "c1"
127.0.0.1:6379> PSUBSCRIBE c* a?
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "c*"
3) (integer) 1
1) "psubscribe"
2) "a?"
3) (integer) 2

总结

Pub/Sub 缺点

  • 发布的消息在 Redis 系统中不能特久化,因此,必须先执行订阅,再等待消息发布,如果先发布了消息,那必该消息由于没有订阅者,消息将被直接丢弃;
  • 消息只管发送对于发布者而言消息是即发即失的,不管接收,也没有 ACK 机制,无法保证消息的消费成功;
  • 以上的缺点导致 Redis 的 Pub/Sub 模式就像个小玩具,在生产环境中几乎无用武之地,为此 Redis5.0 版本新增了 Stream 数据结构,不但支持多播,还支持数据持久化,相比 Pub/Sub 更加的强大。