1、创建redis监听器
@Configuration
public class RedisMessageListener {
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter,
MessageListenerAdapter listenerAdapterTest2){
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter,new PatternTopic(RedisKeyConstant.appendElderPrefix(RedisKeyConstant.REDIS_LISTENER_TOPIC)));
return container;
}
@Bean
public MessageListenerAdapter listenerAdapter(SendRedisMessage receiver){
return new MessageListenerAdapter(receiver,"receiveElderMessage");
}
@Bean
SendRedisMessage receiver(CountDownLatch latch) {
return new SendRedisMessage(latch);
}
@Bean
public CountDownLatch latch(){
return new CountDownLatch(1);
}
}
二、监听队列主题后的处理逻辑
@Slf4j
public class SendRedisMessage {
private CountDownLatch latch;
@Autowired
private PushMessageToVolunteerApp pushMessageToVolunteerApp;
@Autowired
public SendRedisMessage(CountDownLatch latch) {
this.latch = latch;
}
@Bean
public void receiveElderMessage(String json) {
log.info(TimeUtils.ldtToStandardString(LocalDateTime.now())+" 开始消费redis队列order数据,向app端推送消息,消息内容:{}",json);
try {
Map<String,String> map = new HashMap<>(3);
Gson gson = new Gson();
map = gson.fromJson(json,map.getClass());
pushMessageToVolunteerApp.pushElderOrderMessageToApp(map);
log.info(TimeUtils.ldtToStandardString(LocalDateTime.now())+" 消费redis消息队列order数据成功");
} catch (Exception e) {
log.error(TimeUtils.ldtToStandardString(LocalDateTime.now())+" 消费redis消息队列数据失败,失败信息:{}]", e.getMessage());
}finally {
latch.countDown();
}
}
}
三、向队列发送消息
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void send() {
Map<String,String> map = new HashMap<>(5);
map.put("title","发送主题");
map.put("body","发布了新订单");
map.put("order","*******");
stringRedisTemplate.convertAndSend(RedisKeyConstant.appendElderPrefix(RedisKeyConstant.REDIS_LISTENER_TOPIC),new Gson().toJson(map));
}