clean channel shutdown(消息发送成功,ConfirmCallback ack返回为false)

clean channel shutdown; protocol method: #method(reply-code=200, reply-text=OK, class-id=0, method-id=0)

视频出现的问题

@Component
public class RabbitSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.err.println("correlationData: " + correlationData);
            System.err.println("ack: " + ack);
            if(!ack){
                System.err.println("异常处理...." + cause);
            }
        }
    };

    final ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,
                                    String exchange, String routingKey) {
            System.err.println("return exchange: " + exchange + ", routingKey: "
                    + routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);
        }
    };

    public void send(Object message, Map<String, Object> properties) throws Exception {
        MessageHeaders mhs = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, mhs);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        CorrelationData correlationData = new CorrelationData("1234567890");
        rabbitTemplate.convertAndSend("exchange.1", "springboot.test", msg, correlationData);
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {


    @Autowired
    private RabbitSender sender;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    @Test
    public void send() throws Exception {
        Map<String, Object> properties = new HashMap<>();
        properties.put("number", "12345");
        properties.put("send_time", simpleDateFormat.format(new Date()));
        sender.send("Hello RabbitMQ For Spring Boot!", properties);
    }
}

在这里插入图片描述
网上查阅了半天没找到解决问题的,后来想了一下,我是在测试方法中进行测试,当测试方法结束,rabbitmq相关的资源也就关闭了,虽然我们的消息发送出去,但异步的ConfirmCallback却由于资源关闭而出现了上面的问题
所以在测试方法等待一段时间即可

@Test
public void send() throws Exception {
    Map<String, Object> properties = new HashMap<>();
    properties.put("number", "12345");
    properties.put("send_time", simpleDateFormat.format(new Date()));
    sender.send("Hello RabbitMQ For Spring Boot!", properties);
    Thread.sleep(2000);
}

在这里插入图片描述

可以看到成功了!

你可能感兴趣的:(clean channel shutdown(消息发送成功,ConfirmCallback ack返回为false))