目录
Redis 发布订阅
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 客户端可以订阅任意数量的频道。
实例
以下实例演示了发布订阅是如何工作的。在我们实例中我们创建了订阅频道名为 news
subscribe channel [channel ...]
订阅给定的一个或多个频道的信息。
127.0.0.1:6379> subscribe news
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
现在,我们先重新开启个 redis 客户端,然后在同一个频道 news 发布两次消息,订阅者就能接收到消息。
publish channel message
将信息发送到指定的频道。
127.0.0.1:6379> publish news 'oh my god'
(integer) 2
127.0.0.1:6379> publish news 'new new new'
订阅者的客户端会显示如下消息
127.0.0.1:6379> subscribe news
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news"
3) (integer) 1
1) "message"
2) "news"
3) "oh my god"
1) "message"
2) "news"
3) "new new new"
psubscribe pattern [pattern ...]
订阅一个或多个符合给定模式的频道。如: psubscribe new* 就可以订阅new开头后面任意字符的发布
应用场景
聊天室、消息推送