Preface
First look at the callback mechanism:
- No matter whether the message is delivered to the exchange or not, the ConfirmCallback callback is performed, and the delivery is successful ack=true, otherwise it is false
- If the switch matches the queue successfully, the ReturnCallback callback will not be performed, otherwise the ReturnCallback callback will be performed first and then the ConfirmCallback callback will be performed
- If the message is successfully delivered to the exchange but does not match the queue, the ConfirmCallback callback ack is still true
我的springboot版本springBootVersion = '2.2.1.RELEASE'
ConfirmCallback
First you need to configure in yml:
publisher-confirm-type: correlated
/**
* 测试消息确认回调(必须在yml配置publisher-confirm-type: correlated)
*/
@GetMapping("sendConfirmCallback")
public Resp sendConfirmCallback() {
rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
System.out.println("ack:" + ack);
if (!ack) {
System.out.println("异常处理");
}
});
amqpTemplate.convertAndSend("test-queue", "测试ack确认模式");
return Resp.success("ok", null);
}
ReturnCallback
Need to be configured in yml
publisher-returns: true
@Autowired
private AmqpTemplate amqpTemplate;
@Resource
private RabbitTemplate rabbitTemplate;
/**
* 启动消息失败返回,比如路由不到队列时触发回调
* 测试发布回调(必须在yml配置publisher-returns: true)
*/
@GetMapping("sendReturnCallback")
public Resp sendReturnCallback() {
RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> {
System.out.println("========returnCallback=============");
System.out.println("========returnCallback=============");
};
rabbitTemplate.setReturnCallback(returnCallback);
amqpTemplate.convertAndSend("test-", "测试发布回调模式");
return Resp.success("ok", null);
}