redisSerializer) {System.out.println("init messageListener1");return (message, pattern) -> {final byte[] channel = message.getChannel();fina。springboot整合redis实现发布订阅。" />
- 首页 > it技术 > >
//监听处理器1
@Bean("messageListener1")
public MessageListener messageListener1(RedisSerializer> redisSerializer) {
System.out.println("init messageListener1");
return (message, pattern) -> {
final byte[] channel = message.getChannel();
final byte[] body = message.getBody();
String text = redisSerializer.deserialize(body);
String topic = redisSerializer.deserialize(channel);
log.info("client|{},topic|{},text|{}", 1, topic, text);
};
}
//监听处理器2
@Bean("messageListener2")
public MessageListener messageListener2(RedisSerializer> redisSerializer) {
System.out.println("init messageListener2");
return (message, pattern) -> {
final byte[] channel = message.getChannel();
final byte[] body = message.getBody();
String text = redisSerializer.deserialize(body);
String topic = redisSerializer.deserialize(channel);
log.info("client|{},topic|{},text|{}", 2, topic, text);
};
}
//消息序列化
@Bean
public RedisSerializer RedisSerializer() {
return new StringRedisSerializer();
}
//redis监听容器
@Bean("redisMessageListenerContainer")
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory, RedisSerializer> redisSerializer) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(messageListener1(redisSerializer), new PatternTopic("topic1"));
container.addMessageListener(messageListener2(redisSerializer), new PatternTopic("topic1"));
return container;
}
@Autowired
private StringRedisTemplate redisTemplate;
@GetMapping("/publish")
public RestModel publish() {
redisTemplate.convertAndSend("topic1", "nijia-倪佳");
return RestModel.succ();
}
推荐阅读