Redis 发布订阅

Redis 发布订阅(pub/sub)是一种消息通信模式:

  • 发送者(pub)发送消息
  • 订阅者(sub)接收消息

Redis 客户端可以订阅任意数量的频道

订阅频道

1
2
3
4
5
192.168.204.130:6379> subscribe mychannel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "mychannel"
3) (integer) 1

向频道发布信息

1
2
192.168.204.130:6379> publish mychannel "Hello Redis"
(integer) 1

订阅者收到信息

1
2
3
4
5
6
7
8
192.168.204.130:6379> subscribe mychannel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "mychannel"
3) (integer) 1
1) "message"
2) "mychannel"
3) "Hello Redis"

常用命令

命令 说明
PSUBSCRIBE pattern [pattern …] 订阅一个或多个符合给定模式的频道
PUBSUB subcommand [argument [argument …]] 查看订阅与发布系统状态
PUBLISH channel message 将信息发送到指定的频道
PUNSUBSCRIBE [pattern [pattern …]] 退订所有给定模式的频道
SUBSCRIBE channel [channel …] 订阅给定的一个或多个频道的信息
UNSUBSCRIBE [channel [channel …]] 指退订给定的频道