介绍
Redis发布与订阅功能可以让用户将消息同时发送给多个客户端
角色说明
- 发布者(publisher): 发布消息的客户端。
- 频道(channel): 构建在服务器内部,负责接收发布者发送的消息,并将消息转发给频道的订阅者
- 模式(pattern): 构建在服务器内部,负责对频道进行匹配,当被匹配的频道接到消息时,模式也会将消息转发给模式的订阅者
- 订阅者(subscriber): 通过订阅频道或者模式来获取消息的客户端。每个频道或者模式都可以有任意多个订阅者
频道的订阅与消息发布
- B、C、D三个客户端正在订阅mq:msg 频道
- 当客户端A向mq:msg 频道发送消息:HI,该消息将被频道转发给B、C、D三个客户端
模式的订阅与消息发布
- 客户端B、C订阅了模式:mq:m[is]模式,该模式与mq:mig、mq:msg两个频道匹配,当mq:mig或mq:msg频道接收到消息时候,这些消息不仅会被转到给频道的订阅者,也会被转发给客户端C和D
- 例如:mq:mig频道接收到消息后,mq:mig的订阅A会收到消息,同时该消息又会被转发给匹配到的模式:mq:m[is],则客户端B和客户端C也会接收到消息
订阅与发布命令
-
SUBSCRIBE channel [channel …]
订阅一个或多个频道127.0.0.1:6379> subscribe mq:msg Reading messages... (press Ctrl-C to quit) 1) "subscribe" --> 订阅频道时返回的消息 2) "mq:msg" --> 被订阅的频道 3) (integer) 1 --> 客户端目前订阅频道的数据
接收到消息:
1) "message" -->从频道接收到的消息 2) "mq:msg" -->消息来源的频道 3) "hello publis" -->消息内容
-
PSUBSCRIBE pattern [pattern …]
订阅一个或多个模式,
pattern 参数可以包含 glob 风格的匹配符,比如:
mq::*模式:可以匹配 mq::msg、 mq::it 、 mq::yyy::xxx等频道
mq::m[si]g 模式:可以匹配 mq::msg 频道或者 mq::mig 频道
mq::?x 模式“:可以匹配 mq::xx、 mq::ax 、 mq::bx 等频道127.0.0.1:6379> psubscribe mq:m[si]g Reading messages... (press Ctrl-C to quit) 1) "psubscribe" -->订阅模式时返回的信息 2) "mq:m[si]g" -->被订阅的模式 3) (integer) 1 -->客户端目前订阅的模式数量
接收到消息:
1) "pmessage" -->从模式接收到的消息 2) "mq:m[si]g" -->被匹配的模式 3) "mq:msg" -->消息的来源频道(被匹配的频道) 4) "hello publis" -->消息内容
-
UNSUBSCRIBE [channel [channel …]]
退订指定的频道。
如果执行时没有指定任何频道,那么退订已订阅的所有频道 -
PUNSUBSCRIBE [pattern [pattern …]]
退订指定的模式。
如果执行时没有指定任何模式,那么退订已订阅的所有模式 -
PUBLISH channel message
将消息发送至指定的频道,命令返回接收到消息的订阅者数量127.0.0.1:6379> publish mq:msg "hello publis" (integer) 2
订阅状态命令
-
PUBSUB CHANNELS [pattern]
列出目前至少有一个订阅者的频道
如果给定了可选的 pattern 参数,那么只列出与模式相匹配的频道127.0.0.1:6379> pubsub channels 1) "mq:msg"
-
PUBSUB NUMSUB [channel-1 … channel-N]
返回给定频道的订阅者数量127.0.0.1:6379> pubsub numsub mq:msg 1) "mq:msg" 2) (integer) 1 127.0.0.1:6379> pubsub numsub mq:mig 1) "mq:mig" 2) (integer) 0
-
PUBSUB NUMPAT
返回服务器目前被订阅的模式数量127.0.0.1:6379> pubsub numpat (integer) 1 -->服务器目前有一个模式被订阅