Redis中的发布订阅模式是什么?如何使用?

Redis 发布订阅模式(Pub/Sub)允许发送者将消息发布到频道,允许订阅者订阅给定的频道。

当有新消息被发布至频道时,订阅该频道的订阅者将收到通知。这实现了一个简单的消息队列服务。

Redis 发布订阅模式的主要命令有:

  • PUBLISH channel message: 将信息 message 发布到频道 channel。
  • SUBSCRIBE channel [channel …]:订阅给定的一个或多个频道。
  • UNSUBSCRIBE channel [channel …]:退订给定的频道。
  • PSUBSCRIBE pattern [pattern …]:订阅一个或多个给定模式的频道。
  • PUNSUBSCRIBE pattern [pattern …]:退订给定模式的频道。
    例如:
// 订阅者
jedis.subscribe(new JedisPubSub() {
  public void onMessage(String channel, String message) {
    System.out.println("收到频道:" + channel + "的消息:" + message);
  }
}, "channel1");

// 发布者
Jedis jedis = new Jedis("localhost"); 
jedis.publish("channel1", "hello");

当执行 jedis.publish(“channel1”, “hello”); 发布消息时,订阅 channel1 频道的客户端将收到消息通知。