Redis 的 SUBSCRIBE 命令用于订阅给定的一个或多个频道的信息。
192.168.98.70:6379> SUBSCRIBE channel [channel ...]
参数 | 描述 |
---|---|
channel | 要订阅的频道。 |
接收到的信息。
O(N),其中 N 是订阅的频道的数量。
>= 2.0.0
使用 SUBSCRIBE 命令,订阅单个频道
# client-1 订阅 module 频道
192.168.98.70:6379> SUBSCRIBE module
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "module"
3) (integer) 1 #阻塞
# client-2
192.168.98.70:6379> PUBLISH module "Hello haicoder"
(integer) 1
# client-1
1) "message"
2) "module"
3) "Hello haicoder"
我们首先,使用 SUBSCRIBE 命令,订阅 module 频道。使用另一连接,使用 PUBLISH 命令,向 module 频道发布消息。
此时订阅 module 频道的连接收到了来自 module 频道的消息 Hello haicoder。
使用 SUBSCRIBE 命令,可以同时订阅多个频道
# client-1 订阅 module 频道和 category 频道
192.168.98.70:6379> SUBSCRIBE module category
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "module"
3) (integer) 1
1) "subscribe"
2) "category"
3) (integer) 2 # 阻塞
# client-2
192.168.98.70:6379> PUBLISH module "Hello module"
(integer) 1
# client-1
1) "message"
2) "module"
3) "Hello module"
# client-2
192.168.98.70:6379> PUBLISH category "Hello category"
(integer) 1
# client-1
1) "message"
2) "category"
3) "Hello category"
我们首先,使用 SUBSCRIBE 命令,订阅 module 频道。使用另一连接,使用 PUBLISH 命令,向 module 频道发布消息。
此时订阅 module 频道的连接收到了来自 module 频道的消息 Hello haicoder。使用 PUBLISH 命令,向 category 频道发布消息。
此时订阅 category 频道的连接收到了来自 category 频道的消息 Hello category。
Redis 的 SUBSCRIBE 命令用于订阅给定的一个或多个频道的信息。Redis SUBSCRIBE 命令语法:
192.168.98.70:6379> SUBSCRIBE channel [channel ...]