解决rabbitMQ消息发送成功,但ConfirmCallback的ack返回为false问题

  • Post author:
  • Post category:其他


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

今天在学RabbitMQ消息可靠性投递的confirm模式时候,出现上述问题,但这时RabbitMQ的队列中消息已经存在了。只是ack返回为false,如下图:

@SpringBootTest
@RunWith(SpringRunner.class)
public class producerConfirm {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Test
    public void testConfirm() throws InterruptedException {
//        定义回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("回调函数执行了");
                if (ack){
                    System.out.println("已正确发送到exchange");
                }else {
                    System.out.println("发送到exchange失败" + cause);
                }
            }
        });

        rabbitTemplate.convertAndSend(RabbitMQConfirmConfig.EXCHANGE_NAME,"boot.hehe","发送消息");
    }




}

控制台输出为:

当发送方法结束,RabbitMQ相关的资源也就关闭了,虽然我们的消息发送出去,但异步的ConfirmCallback却由于资源关闭而出现了上面问题

所以在发送结束后,让它等待一会

@SpringBootTest
@RunWith(SpringRunner.class)
public class producerConfirm {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Test
    public void testConfirm() throws InterruptedException {
//        定义回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("回调函数执行了");
                if (ack){
                    System.out.println("已正确发送到exchange");
                }else {
                    System.out.println("发送到exchange失败" + cause);
                }
            }
        });

        rabbitTemplate.convertAndSend(RabbitMQConfirmConfig.EXCHANGE_NAME,"boot.hehe","发送消息");
Thread.sleep(2000);
    }





}

再次发送发现可以了



版权声明:本文为dimtem原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。