定义消息实体
@Component
@Data
@Slf4j
public class Msg {
private String channel;
private String msg;
public void receiveMessage(String message, String channel) {
log.info(channel + " 收到消息: " + message);
}
}
定义配置
@Configuration
public class RedisConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// 可以添加多个 messageListener,配置不同的交换机
container.addMessageListener(listenerAdapter, new PatternTopic("channel:test"));
container.addMessageListener(listenerAdapter,new PatternTopic("nnnn"));
return container;
}
/**
* 消息监听器适配器,绑定消息处理器,利用反射技术调用消息处理器的业务方法
* @param receiver
* @return
*/
@Bean
MessageListenerAdapter listenerAdapter(Msg receiver) {
System.out.println("消息适配器1");
return new MessageListenerAdapter(receiver, "receiveMessage");
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
使用
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@PostMapping("msg")
public Object sendMsg(@RequestBody Msg msg){
redisTemplate.convertAndSend(msg.getChannel(),msg.getMsg());
return "OK";
}
}
网友评论