跳至主要內容

发布订阅

Mr.Liu大约 2 分钟数据库NoSQLRedis

发布订阅

进程间的一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。Redis 客户端可以订阅任意数量的频道。

下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

img
img

当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

img
img

命令

下表列出了 redis 发布订阅常用命令:

序号命令及描述
1PSUBSCRIBE pattern pattern ... 订阅一个或多个符合给定模式的频道。
2PUBSUB subcommand [argument [argument ...]] 查看订阅与发布系统状态。
3PUBLISH channel message 将信息发送到指定的频道。
4PUNSUBSCRIBE [pattern [pattern ...]] 退订所有给定模式的频道。
5SUBSCRIBE channel [channel ...] 订阅给定的一个或多个频道的信息。
6UNSUBSCRIBE [channel [channel ...]] 指退订给定的频道。

案例

先订阅后发布后才能收到消息, 1、可以一次性订阅多个,SUBSCRIBE c1 c2 c3

2、消息发布,PUBLISH c1 helloworld

客户端1客户端2
127.0.0.1:6379> SUBSCRIBE c1 c2 c3
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (integer) 1
1) "subscribe"
2) "c2"
3) (integer) 2
1) "subscribe"
2) "c3"
3) (integer) 3
127.0.0.1:6379> PUBLISH c1 helloworld
(integer) 1
1) "message"
2) "c1"
3) "helloworld"

3、订阅多个,通配符*PSUBSCRIBE news*

4、收取消息,PUBLISH new1 redis2015

客户端1客户端2
127.0.0.1:6379> PSUBSCRIBE news*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "news*"
3) (integer) 1
127.0.0.1:6379> PUBLISH news1 news2022
(integer) 1
1) "pmessage"
2) "news*"
3) "news1"
4) "news2022"
127.0.0.1:6379> PUBLISH news121 news20221211
(integer) 1
1) "pmessage"
2) "news*"
3) "news121"
4) "news20221211"