Redis发布订阅(pub/sub)是一种快速、稳定的发布/订阅的消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息,微信、微博、关注系统
Redis客户端可以订阅任意数量的频道
订阅/发布消息图:
第一个:消息发送者,第二个:频道(channel),第三个:消息订阅者
下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:
当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:
Redis 发布订阅命令
下表列出了 redis 发布订阅常用命令:
xshell 中命令
127.0.0.1:6379> help @pubsub
PSUBSCRIBE pattern [pattern ...]
summary: Listen for messages published to channels matching the given patterns
since: 2.0.0
PUBLISH channel message
summary: Post a message to a channel
since: 2.0.0
PUBSUB subcommand [argument [argument ...]]
summary: Inspect the state of the Pub/Sub subsystem
since: 2.8.0
PUNSUBSCRIBE [pattern [pattern ...]]
summary: Stop listening for messages posted to channels matching the given patterns
since: 2.0.0
SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0.0
UNSUBSCRIBE [channel [channel ...]]
summary: Stop listening for messages posted to the given channels
since: 2.0.0
127.0.0.1:6379>
案例演示:
以下实例演示了发布订阅是如何工作的,需要开启两个 redis-cli 客户端。
1、启动redis
[root@iZ2ze5v2vdwv6veyksylhxZ bin]# redis-server muzhen_config/redis.conf
[root@iZ2ze5v2vdwv6veyksylhxZ bin]# redis-cli -p 6379
127.0.0.1:6379> ping
PONG
2、订阅端
在我们实例中我们创建了订阅频道名为 lian:
# 第一个 redis-cli 客户端
127.0.0.1:6379> SUBSCRIBE lian #订阅一个频道 msb
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "lian"
3) (integer) 1
#等待读取推送的消息
1) "message" #消息
2) "lian" #频道名,这里指的是msb频道的消息
3) "love" #消息的具体内容
1) "message"
2) "lian"
3) "hello-redis"
3、发送端,发布消息后,订阅者会自动收到消息
我们先重新开启个 redis 客户端,然后在同一个频道 lian 发布两次消息,订阅者就能接收到消息
# # 第二个 redis-cli 客户端
[root@iZ2ze5v2vdwv6veyksylhxZ bin]# redis-server muzhen_config/redis.conf
[root@iZ2ze5v2vdwv6veyksylhxZ bin]# redis-cli -p 6379
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> PUBLISH lian love #发布者发布消息到频道
(integer) 1
127.0.0.1:6379> PUBLISH lian hello-redis
(integer) 1
127.0.0.1:6379>
gif 演示如下:
1、开启本地 Redis 服务,开启两个 redis-cli 客户端
2、在第一个 redis-cli 客户端输入 SUBSCRIBE runoobChat,意思是订阅 runoobChat 频道
3、在第二个 redis-cli 客户端输入 PUBLISH runoobChat “Redis PUBLISH test” 往 runoobChat 频道发送消息,这个时候在第一个 redis-cli 客户端就会看到由第二个 redis-cli 客户端发送的测试消息