1、配置文件增加如下内容:
application.yml修改如下:
spring: rabbitmq: publisher-confirm-type: simple #开启confirm机制 publisher-returns: true #开启return机制
2、增加配置类:
1 package com.yas.rabbitmqboot.config; 2 3 import org.springframework.amqp.core.ReturnedMessage; 4 import org.springframework.amqp.rabbit.connection.CorrelationData; 5 import org.springframework.amqp.rabbit.core.RabbitTemplate; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Component; 8 9 import javax.annotation.PostConstruct; 10 11 @Component 12 public class PublisherConfirmAndReturnConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback { 13 14 @Autowired 15 RabbitTemplate rabbitTemplate; 16 17 @PostConstruct 18 public void initMethod() { 19 rabbitTemplate.setConfirmCallback(this); 20 rabbitTemplate.setReturnsCallback(this); 21 } 22 23 @Override 24 public void confirm(CorrelationData correlationData, boolean b, String s) { 25 if (b) { 26 System.out.println("消息已经送达Exchange,ack已发"); 27 } else { 28 System.out.println("消息没有送达Exchange"); 29 } 30 } 31 32 @Override 33 public void returnedMessage(ReturnedMessage returnedMessage) { 34 System.out.println("消息没有送到队列中"); 35 } 36 }