利用spring-boot结合redis进行消息的发布与订阅:
发布:
class Publish {
private static String topicName = “Topic:chat”;
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter ) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer ();
redisMessageListenerContainer.setConnectionFactory(connectionFactory);
redisMessageListenerContainer.addMessageListenerAdapter(messageListenerAdapter ,new PatternTopic(topicName ));
return redisMessageListenerContainer;
}
@Bean
MessageListenerAdapter messageListenerAdapter(Receiver recevier){
return new MessageListenerAdapter (recevier,"receiveMessage");
}
@Bean
Receiver recevier(@Value("Receiver-1") String name) {
return new Receiver(name);
}
public static main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Publish .class,args);
StringRedisTemple stringRedisTemple = ctx.getBean(StringRedisTemple.class);
stringRedisTemple.convertAndSend(topicName ,"HAHAHAHAHAHA");
}
}
订阅:
class Receiver {
private String name;
@Autowired
public Receiver(String name) {
this.name = name;
}
public void receiveMessage(String message) {
System.ount.println(name + message);
}
}