Redis 设计与实现 (六)--发布订阅

时间:2021-09-22 10:11:54

发布订阅

相关命令:publish(发布)  subscribe(订阅)  psubscribe(支持通配符匹配)

发布者--频道--订阅者(发布和订阅都是客户端频道是服务端)

Redis  设计与实现 (六)--发布订阅

1、publish- subscribe 模式

开启一个命令窗体,redis订阅者:

# redis-cli
127.0.0.1:> subscribe channel_1
Reading messages... (press Ctrl-C to quit)
) "subscribe"
) "channel_1"
) (integer)

然后再开启一个命令窗体为redis 发布者:

# redis-cli
127.0.0.1:6379> publish channel_1 "hello"
(integer) 2
127.0.0.1:6379> publish channel_1 "world"
(integer) 2

然后再看看订阅者的反馈:

127.0.0.1:> subscribe channel_1
Reading messages... (press Ctrl-C to quit)
) "subscribe"
) "channel_1"
) (integer)
) "message"//订阅消息
) "channel_1"//频道
) "hello"//消息体
) "message"//消息
) "channel_1"//订阅频道
) "world"//消息

收到 channle_1=>hello 和 channel_1=>world,发布者广播的消息。

2、publish-psubscribe 模式

首先,定义订阅者订阅

# redis-cli
127.0.0.1:6379> psubscribe server-*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "server-*"
3) (integer) 1

其次,定义发布者server-1

# redis-cli
127.0.0.1:> publish server- "server-1"

再次,定义发布者server-2

# redis-cli
127.0.0.1:> publish server- "server_2"

最后,查看订阅者订阅变化

# redis-cli
127.0.0.1:> psubscribe server-*
Reading messages... (press Ctrl-C to quit)
) "psubscribe"
) "server-*"
) (integer)
) "pmessage"
) "server-*"
) "server-1"//server-1
) "server-1"
) "pmessage"
) "server-*"
) "server-2"//server-2
) "server_2"

3、退订

unsubscribe <频道s>

punsubscribe <频道s>

4、查看订阅信息 PUBSUB CHANNELS