By default, a Message is removed from the Queue if it is properly received by the consumer

If a Queue is not subscribed to by any consumer, the messages in the Queue are cached, sent immediately when a consumer subscribed, and removed from the Queue when they were properly received by the consumer

Message sending confirmation

What constitutes a failure or success of a sent message? How to confirm?

  • Failed to confirm message routing when the message could not be routed to the queue. When a message is routed successfully, a confirmation message is sent to all queues that need to be sent successfully. For the persistent queue, the message is written to disk. For the mirroring queue, the message is received successfully

ConfirmCallback

  • By implementing the ConfirmCallback interface, messages sent to the Broker trigger a callback to confirm that the message has reached the Broker server, that is, only that it has reached the Exchange correctly
@Componentpublic class RabbitTemplateConfig implements RabbitTemplate.ConfirmCallback{ @Autowired private RabbitTemplate  rabbitTemplate; @PostConstruct public void init(){ rabbitTemplate.setConfirmCallback(this); Override public void confirm(CorrelationData CorrelationData, Boolean ack, String cause) {system.out.println (" message unique id: "+correlationData); System.out.println(" confirm result: "+ack); System.out.println(" cause: "+cause); }Copy the code
  • You also need to add configuration to the configuration file
spring:
  rabbitmq:
    publisher-confirms: true
Copy the code

ReturnCallback

  • By implementing the ReturnCallback interface, a message is returned on startup failure, such as a callback triggered when the route is not in the queue
@Componentpublic class RabbitTemplateConfig implements RabbitTemplate.ReturnCallback{    @Autowired
    private RabbitTemplate rabbitTemplate;    @PostConstruct
    public void init(){
        rabbitTemplate.setReturnCallback(this);             //指定 ReturnCallback
    }    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("消息主体 message : "+message);
        System.out.println("消息主体 message : "+replyCode);
        System.out.println("描述:"+replyText);
        System.out.println("消息使用的交换器 exchange : "+exchange);
        System.out.println("消息使用的路由键 routing : "+routingKey);
    }
}
Copy the code