Redis Subscribe&publish

redis用了两年之久,才发现有这么一个订阅广播的强大功能。
前端时间在研究socket.io (nodejs) 与laravel 的广播事件中发现了它,强大之极。

Redis 通过 PUBLISH 、 SUBSCRIBE 和 PSUBSCRIBE 等命令实现发布和订阅功能

PUBLISH 命令用于向给定的频道发送信息,返回值为接收到信息的订阅者数量

redis> PUBLISH test-channel hello 这时,redis会向订阅test-channel的客户端发送 “hello” 这条信息

所谓订阅 test-channel 的订阅者如下方

redis> SUBSCRIBE test-channel
  Reading messages... (press Ctrl-C to quit)

  1. "subscribe" # 订阅反馈
  2. "chatroom" # 订阅的频道
  3. (integer) 1 # 目前客户端已订阅频道/模式的数量
  4. "message" # 信息
  5. "channel" # 发送信息的频道
  6. "hello" # 信息内容

eg: SUBSCRIBE 还可以订阅多个频道,这样一来它接收到的信息就可能来自多个频道

PSUBSCRIBE 提供了一种订阅符合给定模式的所有频道的方法,比如说,使用 it.* 为输入,就可以订阅所有以 it. 开头的频道,比如 it.news 、 it.blog 、 it.tweets ,诸如此类:   
redis> PSUBSCRIBE it.*   
Reading messages... (press Ctrl-C to quit)

  1. "psubscribe"
  2. "it.*"
  3. (integer) 1
  4. "pmessage"
  5. "it.*" # 匹配的模式
  6. "it.news" # 消息的来源频道
  7. "Redis 2.6rc5 release" # 消息内容
  8. "pmessage"
  9. "it.*"
  10. "it.blog"
  11. "Why NoSQL matters"
  12. "pmessage"
  13. "it.*"
  14. "it.tweet"
  15. "@redis: when will the 2.6 stable release?"

还有更多的redis功能都等着我们去学习!!!

happy hack 2017-07-01

你可能感兴趣的:(Redis Subscribe&publish)