rabbitMq可靠性投递之配置(消息至交换机,至队列不通的回调)
@Bean
public RabbitTemplate rabbitTemplate(CachingConnectionFactory factory) {
//若使用confirm-callback ,必须要配置publisherConfirms 为true
factory.setpublisherConfirms(true);
// 若使用return-callback,必须要配置publisherReturns为true
factory.setPublisherReturns(true);
RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
//使用return-callback时必须设置mandatory为true,或者在配置中设置mandatory-expression的值为true
rabbitTemplate.setMandatory(true); // 如果消息没有到exchange,则confirm回调,ack=false;
// 如果消息到达exchange,则confirm回调,ack=true
rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
@Override
/** * correlationData 配置 * cause原因 * ack 确认 */
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (ack) {
System.out.println("消息发送成功:correlationData({}),ack({}),cause({})" + correlationData + ":" + ack + ":" + cause);
} else {
System.out.println("消息发送成功:correlationData({}),ack({}),cause({})" + correlationData + ":" + ack + ":" + cause);
}
}
});
//如果exchange到queue成功,则不回调return; 如果exchange到queue失败, 则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
@Override
public void returnedMessage(ReturnedMessage returnedMessage) {
System.out.println("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}" + JSON.toJSONString(returnedMessage));
}
});
return rabbitTemplate;
}
本文来自博客园,作者:余生请多指教ANT,转载请注明原文链接:https://www.cnblogs.com/wangbiaohistory/p/14630493.html

浙公网安备 33010602011771号