目录
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息 ——— 微信 、微博的 关注系统
Redis 客户端可以订阅任意数量的频道
订阅/发布消息图:
- 消息发布者
- 频道
- 消息订阅者
下图是频道 channel1 , 以及订阅这个频道的三个客户端 ——- cilent2,cilent5 和 cilent1 之间的关系
当有消息通过Publish 命令发送给频道 channel1 时,这个消息就会被它发送给订阅它的三个客户端
命令
redis 发布订阅常用命令:
序号 | 命令及描述 |
---|---|
1 | PSUBSCRIBE pattern [pattern …] 订阅一个或多个符合给定模式的频道。 |
2 | PUBSUB subcommand [argument [argument …]] 查看订阅与发布系统状态。 |
3 | PUBLISH channel message 将信息发送到指定的频道。 |
4 | PUNSUBSCRIBE [pattern [pattern …]] 退订所有给定模式的频道。 |
5 | SUBSCRIBE channel channel …] 订阅给定的一个或多个频道的信息。 |
6 | UNSUBSCRIBE [channel [channel …]] 指退订给定的频道。 |
测试
订阅信息:
127.0.0.1:6379> SUBSCRIBE gh # 订阅一个频道 gh
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "gh"
3) (integer) 1
# 等待推送消息
1) "message" # 消息
2) "gh" # 哪个频道的消息
3) "hello,word" # 消息的具体内容
1) "message"
2) "gh"
3) "hello,redis"
发送端:
127.0.0.1:6379> PUBLISH gh "hello,word" # 发布者发布消息到频道
(integer) 1
127.0.0.1:6379> PUBLISH gh "hello,redis"
(integer) 1
127.0.0.1:6379>
使用场景:
1、实时消息系统!
2、事实聊天!(频道当做聊天室,将信息回显给所有人即可!)
3、订阅,关注系统都是可以的!
稍微复杂的场景我们就会使用消息中间件MQ