Redis 发布订阅

197 阅读1分钟
  • 简介

Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。用于客户端之间相互通信。

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

  • 命令
序号 命令 描述
1 SUBSCRIBE channel[channel...] 订阅给定的一个或多个频道的信息。
2 PUBLISH channel message 将信息发送到指定的频道。
3& PSUBSCRIBE pattern [pattern ...] 订阅一个或多个符合给定模式的频道。
4 UNSUBSCRIBE [channel [channel ...]] 指退订给定的频道。
5 PUNSUBSCRIBE [pattern [pattern ...]] 退订所有给定模式的频道。
6& PUBSUB subcommand [argument [argument ...]] 查看订阅与发布系统状态。
  • 实例
客户端1 订阅 channel
subscribe channel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel"
3) (integer) 1

客户端2 发布在channel 发布信息
127.0.0.1:6379> publish channel "redis sub pub"
(integer) 1

客户端1 收到客户端2 发布的信息
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel"
3) (integer) 1
1) "message"
2) "channel"
3) "redis sub pub"