消息回退可以避免由于路由不通造成的消息丢失。 具体方法可以参照: blog.csdn.net/weixin_5061…
其中需要注意点: 在注入的代码里需要加入: mandatory参数的设置
@SuppressWarnings("all")
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback , RabbitTemplate.ReturnCallback{
@Autowired
private RabbitTemplate rabbitTemplate;
// 注入
@PostConstruct
public void init(){
rabbitTemplate.setConfirmCallback(this);
rabbitTemplate.setReturnCallback(this);
rabbitTemplate.setMandatory(true); // 这一行省略可能导致无法回退消息
}
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
String id=correlationData!=null?correlationData.getId():"";
if(ack){
log.info("交换机已经收到 id 为:{}的消息",id); }else{
log.info("交换机还未收到 id 为:{}消息,由于原因:{}",id,cause); }
}
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println("ooooooo消息退回");
log.error("消息{},被交换机{}退回,退回的原因:{},路由Key:{}",
new String(message.getBody())
,exchange
,replyText
,routingKey
);
}
}