【redis】redis的发布订阅简述

之前写过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值