先要在文件中配置发送确认
spring:
application:
name: XXX
rabbitmq:
host: 192.168.0.168
port: 5672
username: guest
password: guest
virtual-host: ht
publisher-confirm-type: correlated #开启到交换机确认
publisher-returns: true #开启到队列确认
@Configuration()
public class RabbitMQConfig {
public final static String EXCHANGE = "direct.exchange.ht";
public static final String ROUTINGKEY = "ht.routingkey";
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* 定义消息发交换机回调处理
*/
RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
if(b){
System.out.println("消息成功发送到交换机");
}else{
System.out.println("消息发送失败,要写失败后的处理,如保存到数据为以后再发。。。"+s);
}
}
};
/**
* 定义消息从交换机到队列报错处理
*/
RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
@Override
public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
System.out.println(String.format("消息由交换机到队列报错了。。,message[%s], replyCode[%s], replyText[%s], exchange[%s], routingKey[%s]",
message, replyCode, replyText, exchange, routingKey));
}
};
/**
* 消息报错回调
*/
@Bean
public void initCallback(){
rabbitTemplate.setConfirmCallback(confirmCallback);
rabbitTemplate.setReturnCallback(returnCallback);
}
/**
* 自动创建交换机
* @return
*/
@Bean
public DirectExchange exchange() { // 使用直连的模式
return new DirectExchange(EXCHANGE, true, true);
}
/**
* 自动创建队列
* @return
*/
@Bean
public Queue htqueueAdd() {
return new Queue("queue.ht.test", true);
}
/**
* 队队绑定关系
* @return
*/
@Bean
public Binding bindinghtquueu() {
return BindingBuilder.bind(htqueueAdd()).to(exchange()).with(ROUTINGKEY);
}
}