3.4 发布订阅

redis作为一个pub/sub server,在订阅者和发布者之间起到了消息路由的功能。订阅者可以通过subscribe和psubscribe命令向redis server订阅自己感兴趣的消息类型,redis将消息类型称为频道(channel)。当发布者通过publish命令向redis server发送特定类型的消息时。订阅该消息类型的全部client都会收到此消息。这里消息的传递是多对多的。一个client可以订阅多个 channel,也可以向多个channel发送消息。

  1. 终端A
  2. 127.0.0.1:6379> subscribe comments
  3. Reading messages... (press Ctrl-C to quit)
  4. 1) "subscribe"
  5. 2) "comments"
  6. 3) (integer) 1
  7. 终端B:
  8. 127.0.0.1:6379> subscribe comments
  9. Reading messages... (press Ctrl-C to quit)
  10. 1) "subscribe"
  11. 2) "comments"
  12. 3) (integer) 1
  13. 终端C
  14. 127.0.0.1:6379> publish comments good!
  15. (integer) 2
  16. 终端A:
  17. 127.0.0.1:6379> subscribe comments
  18. Reading messages... (press Ctrl-C to quit)
  19. 1) "subscribe"
  20. 2) "comments"
  21. 3) (integer) 1
  22. 1) "message"
  23. 2) "comments"
  24. 3) "good!"
  25. 终端B
  26. 127.0.0.1:6379> subscribe comments
  27. Reading messages... (press Ctrl-C to quit)
  28. 1) "subscribe"
  29. 2) "comments"
  30. 3) (integer) 1
  31. 1) "message"
  32. 2) "comments"
  33. 3) "good!"

可以使用psubscribe通过通配符进行多个channel的订阅