Redis 的 PSUBSCRIBE 命令订阅一个或多个符合给定模式的频道。
每个模式以 *
作为匹配符,比如 module*
匹配所有以 module 开头的频道(module.html 、 module.js 、 module.tool 等等)。 html.*
匹配所有以 html. 开头的频道( html.html 、 html.html5 等等),诸如此类。
192.168.98.70:6379> PSUBSCRIBE pattern [pattern ...]
参数 | 描述 |
---|---|
pattern | 订阅的模式。 |
接收到的信息。
O(N), N 是订阅的模式的数量。
>= 2.0.0
使用 PSUBSCRIBE 命令,订阅一个符合给定模式的频道
# 订阅 module.* 频道
192.168.98.70:6379> PSUBSCRIBE module.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "module.*"
3) (integer) 1 # 阻塞
# 重新打开一个终端,发布
192.168.98.70:6379> PUBLISH module.html html
(integer) 1
# 阻塞频道有数据
1) "pmessage"
2) "module.*"
3) "module.html"
4) "html"
192.168.98.70:6379> PUBLISH module.js vue
(integer) 1
# 阻塞频道有数据
1) "pmessage"
2) "module.*"
3) "module.js"
4) "vue"
192.168.98.70:6379> PUBLISH redis redis
(integer) 0
192.168.98.70:6379> PSUBSCRIBE module.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "module.*"
3) (integer) 1
1) "pmessage"
2) "module.*"
3) "module.html"
4) "html"
1) "pmessage"
2) "module.*"
3) "module.js"
4) "vue"
我们首先,使用 PSUBSCRIBE 订阅以 module. 开头的队列,此时终端被阻塞。我们打开另一个终端,向 module.html 发送 html 消息。
发完消息后,原来订阅的阻塞队列收到了 pmessage,匹配的模式是 module.*
, 来自 module.html,内容是 html。再次向 module.js 发送 vue 消息。
在发完消息后,原来订阅的阻塞队列收到了 pmessage,匹配的模式是 module.*
, 来自 module.js,内容是 vue。
再次向 redis 发送 redis 消息。发完消息后,原来订阅的阻塞队列继续被阻塞,因为 redis 不能匹配模式 module.*
。
使用 PSUBSCRIBE 命令,可以同时订阅多个符合给定模式的频道
# 订阅 module.* 和 category.* 频道
192.168.98.70:6379> PSUBSCRIBE module.* category.*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "module.*"
3) (integer) 1
1) "psubscribe"
2) "category.*"
3) (integer) 2 # 阻塞
# 重新打开一个终端,发布
192.168.98.70:6379> PUBLISH module.html html
(integer) 1
# 阻塞频道有数据
1) "pmessage"
2) "module.*"
3) "module.html"
4) "html"
192.168.98.70:6379> PUBLISH module.js vue
(integer) 1
# 阻塞频道有数据
1) "pmessage"
2) "module.*"
3) "module.js"
4) "vue"
192.168.98.70:6379> PUBLISH category.html5 html5
(integer) 1
# 阻塞频道有数据
1) "pmessage"
2) "category.*"
3) "category.html5"
4) "html5"
我们首先,使用 PSUBSCRIBE 同时订阅以 module. 开头和以 category. 开头的队列,此时终端被阻塞。打开另一个终端,向 module.html 发送 html 消息。
发完消息后,原来订阅的阻塞队列收到了 pmessage,匹配的模式是 module.*
, 来自 module.html,内容是 html。
再次向 module.js 发送 vue 消息。发完消息后,原来订阅的阻塞队列收到了 pmessage,匹配的模式是 module.*
, 来自 module.js,内容是 vue。
再次向 category.html5 发送 html5 消息。发完消息后,原来订阅的阻塞队列收到了 pmessage,匹配的模式是 category.*
, 来自 category.html5,内容是 html5。
Redis 的 PSUBSCRIBE 命令订阅一个或多个符合给定模式的频道。Redis PSUBSCRIBE 命令语法:
192.168.98.70:6379> PSUBSCRIBE pattern [pattern ...]