Redis发布订阅PUB/SUB
Redis发布订阅PUB/SUB是一种消息通信模式,发送者PUB发送消息,订阅者SUB接收消息。Redis客户端可以订阅任意数量的频道,一个通道CHANNEL可以被多个客户端订阅,当一条消息发送到CHANNEL中去后所有订阅的客户端都会接收到此消息。
一、Redis客户端命令
- 订阅一个或多个频道
SUBSCRIBE channel[channel ...]
- 取消客户端对一个或多个频道的订阅
UNSUBSCRIBE [channel [channel ...]]
- 订阅一个或多个符合给定模式的频道
PSUBSCRIBE pattern [pattern ...]
- 取消一个或多个符合给定模式的频道的订阅
PUNSUBSCRIBE [pattern [pattern ...]]
- 向通道中发送消息
PUBLISH channel message
- 查询活跃channel列表
PUBSUB CHANNELS [pattern]
- 查询已订阅模式的数量
PUBSUB NUMPAT
二、springboot发布订阅频道
- 定义Receiver实体类
public class Receiver {
private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
private AtomicInteger counter = new AtomicInteger();
public void receiveMessage(String message) {
LOGGER.info("Received <" + message + ">");
counter.incrementAndGet();
}
public int getCount() {
return counter.get();
}
}
- 定义订阅消息通道配置类
@Configuration
public class RedisConfig {
@Bean
public String register(RedisMessageListenerContainer factory, MessageListenerAdapter messageListenerAdapter) {
factory.addMessageListener(messageListenerAdapter, PatternTopic.of("test"));
factory.addMessageListener(messageListenerAdapter, ChannelTopic.of("test1"));
return "success";
}
@Bean
public String register1(@Qualifier("test1RedisMessageListenerContainer") RedisMessageListenerContainer factory, MessageListenerAdapter messageListenerAdapter) {
factory.addMessageListener(messageListenerAdapter, PatternTopic.of("test"));
factory.addMessageListener(messageListenerAdapter, PatternTopic.of("test1"));
return "success";
}
@Bean
public MessageListenerAdapter messageListenerAdapter() {
return new MessageListenerAdapter(new Receiver(), "receiveMessage");
}
}
上述是基于自定义redis sdk,支持多个RedisMessageListenerContainer
- 向频道中发送消息
@GetMapping("send")
public void send() {
RedisDbFactory.getStringRedisTemplate().convertAndSend("test", "测试消息");
RedisDbFactory.getStringRedisTemplate("test1").convertAndSend("test1", "测试消息1");
}
开源SDK:https://github.com/mingyang66/spring-parent