Redis 设计与实现 (六)--发布订阅
发布订阅
相关命令:publish(发布) subscribe(订阅) psubscribe(支持通配符匹配)
发布者--频道--订阅者(发布和订阅都是客户端频道是服务端)
1、publish- subscribe 模式
开启一个命令窗体,redis订阅者:
# redis-cli 127.0.0.1:6379> subscribe channel_1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel_1" 3) (integer) 1
然后再开启一个命令窗体为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:6379> subscribe channel_1 Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "channel_1" 3) (integer) 1 1) "message"//订阅消息 2) "channel_1"//频道 3) "hello"//消息体 1) "message"//消息 2) "channel_1"//订阅频道 3) "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:6379> publish server-1 "server-1"
再次,定义发布者server-2
# redis-cli 127.0.0.1:6379> publish server-2 "server_2"
最后,查看订阅者订阅变化
# redis-cli 127.0.0.1:6379> psubscribe server-* Reading messages... (press Ctrl-C to quit) 1) "psubscribe" 2) "server-*" 3) (integer) 1 1) "pmessage" 2) "server-*" 3) "server-1"//server-1 4) "server-1" 1) "pmessage" 2) "server-*" 3) "server-2"//server-2 4) "server_2"
3、退订
unsubscribe <频道s>
punsubscribe <频道s>
4、查看订阅信息 PUBSUB CHANNELS
更多精彩原创心得,请关注微信公众号: 梯形