Redis中的订阅模式

redis中的客户端可以订阅一个自定义的频道,接受来自该频道的消息

订阅

订阅指定频道-SUBSCRIBE

SUBSCRIBE channel [channel2]...
SUBSCRIBE 频道名 [频道名2]...

127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1

订阅匹配频道-PSUBSCRIBE

匹配模式可以订阅名称匹配符合的频道
PSUBSCRIBE channel*
代表订阅channel开头的频道

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

匹配模式要注意,匹配的名称可以在以后出现,但凡是知道会有哪些频道出现,都尽量不要用这个模式,可能会在之后出现一个你没有预料到的频道的消息

发布

PUBLISH

PUBLISH channel message
向特定频道发送消息

127.0.0.1:6379> publish channel3 "test channel 3"
(integer) 1
127.0.0.1:6379> publish channel1 "test channel 1"
(integer) 3

返回的数值是接受到该消息的客户端数量

Redis的发布订阅系统也要注意一些问题,网络传输可能掉线问题

原文地址:https://www.cnblogs.com/liangshu/p/12418880.html