return 退回模式介绍及实现:
Return Listener用于处理一些不可路由的消息
我们的消息生产者,通过制定一个Exchange和RoutingKey,把消息送达到某一个队列中去,然后我们消费者监听队列,进行消费处理。但是在某些情况下,如果我们在发送消息的时候,当前的exchange不存在或指定的路由key路由不到,这个时候我们需要监听这种不可达的消息,Return Listener
1、配置文件设置
# 开启返回
publisher-returns: true
2、实现RabbitTemplate.ReturnCallback接口,实现returnedMessage方法
@Service("RabbitMqService")
public class RabbitMqServiceImpl implements RabbitMqService, RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback{
/**
*
* @param message 消息主体
* @param replyCode 返回code
* @param replyText 返回信息
* @param exchange 交换机
* @param routingKey 路由key
*/
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println("return方法被执行...");
System.out.println("消息主体:"+new String(message.getBody()));
System.out.println("replyCode:"+replyCode);
System.out.println("replyText:"+replyText);
System.out.println("exchange:"+exchange);
System.out.println("routingKey:"+routingKey);
}
}
3、注入RabbitTemplate模版
@Autowired
private RabbitTemplate rabbitTemplate;
4、初始化设置
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
}
5、更改路由key,发送数据测试
@Override
public void sendMessage(String message) {
CorrelationData correlationData = new CorrelationData("1");
//FFF是不存在的路由key
rabbitTemplate.convertAndSend(RabbitMqConfig.DIRECT_EXCHANGE,"FFF",message,correlationData);
}
6、启动测试:
package com.java996.producer;
import com.java996.producer.Service.RabbitMqService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class ProducerApp {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ProducerApp.class,args);
RabbitMqService rabbitMqService = (RabbitMqService) context.getBean("RabbitMqService");
rabbitMqService.sendMessage("confirm确认测试");
}
}
7、控制台: