之前写过redis的list类型,可以使用阻塞blpop等命令,如果List为空,会阻塞的去等待list,直到list有数据了,再去弹出。如果我们想要去实现如聊天功能,显然list的功能不能够满足需求。这时可以使用redis的发布订阅,其命令如下:
127.0.0.1:6379> help @pubsub
PSUBSCRIBE pattern [pattern ...]
summary: Listen for messages published to channels matching the given patterns
since: 2.0.0
PUBLISH channel message
summary: Post a message to a channel
since: 2.0.0
PUBSUB
summary: A container for Pub/Sub commands
since: 2.8.0
PUBSUB CHANNELS [pattern]
summary: List active channels
since: 2.8.0
PUBSUB HELP
summary: Show helpful text about the different subcommands
since: 6.2.0
PUBSUB NUMPAT
summary: Get the count of unique patterns pattern subscriptions
since: 2.8.0
PUBSUB NUMSUB [channel [channel ...]]
summary: Get the count of subscribers for channels
since: 2.8.0
PUBSUB SHARDCHANNELS [pattern]
summary: List active shard channels
since: 7.0.0
PUBSUB SHARDNUMSUB [shardchannel [shardchannel ...]]
summary: Get the count of subscribers for shard channels
since: 7.0.0
PUNSUBSCRIBE [pattern [pattern ...]]
summary: Stop listening for messages posted to channels matching the given patterns
since: 2.0.0
SPUBLISH shardchannel message
summary: Post a message to a shard channel
since: 7.0.0
SSUBSCRIBE shardchannel [shardchannel ...]
summary: Listen for messages published to the given shard channels
since: 7.0.0
SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0.0
SUNSUBSCRIBE [shardchannel [shardchannel ...]]
summary: Stop listening for messages posted to the given shard channels
since: 7.0.0
UNSUBSCRIBE [channel [channel ...]]
summary: Stop listening for messages posted to the given channels
since: 2.0.0
发布订阅,是用户对于redis中的一个channel去发布消息,订阅了这个channel的用户都能够收到发布的这个消息。
示例如下:
首先一个用户A订阅channel
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
用户B对channel发布一条消息
127.0.0.1:6379> publish channel1 hello
(integer) 1
用户A就会收到消息如下:
127.0.0.1:6379> subscribe channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1
1) "message"
2) "channel1"
3) "hello"
其中1是类型,
类型共有3个[1]
subscribe: 表示我们成功订阅到响应的第二个元素提供的频道。第三个参数代表我们现在订阅的频道的数量。
unsubscribe:表示我们成功取消订阅到响应的第二个元素提供的频道。第三个参数代表我们目前订阅的频道的数量。当最后一个参数是0的时候,我们不再订阅到任何频道。当我们在Pub/Sub以外状态,客户端可以发出任何redis命令。
message: 这是另外一个客户端发出的发布命令的结果。第二个元素是来源频道的名称,第三个参数是实际消息的内容。
参考文章:
[1],Pub/Sub