如果队列不存在则消息丢失

Messages lost if queue does not exist

当我们将消息发送到 RabbitMQ 时,如果队列不存在,消息将丢失而不会引发任何错误。

消息将发布到哪里?死队列?

这就是 RabbitMQ 的设计方式 - 发布者发布到交换器,而不是队列。

如果没有队列绑定(如果交换需要一个匹配的路由键),消息将被简单地丢弃。

您可以 enable publisher returns 并在发布时设置 mandatory 标志,代理将 return 消息(但它到达不同的线程,而不是发布线程)。

您的消息可以返回给您

如果没有队列绑定到交换机。要接收它们并且不丢失这些消息,您必须执行以下操作:

1。将这些属性添加到您的 application.yml

spring:
  rabbitmq:
    publisher-confirm-type: correlated
    publisher-returns: true
    template:
      mandatory: true

2。创建 RabbitConfirmCallback

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitConfirmCallback implements RabbitTemplate.ConfirmCallback {
    private static final Logger logger = LoggerFactory.getLogger(RabbitConfirmCallback.class);

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack && correlationData != null && correlationData.getId() != null) {

            Message returnedMessage = correlationData.getReturnedMessage();
            String dataId = correlationData.getId();

            if (returnedMessage != null) {
                logger.error("Message wasn't delivered to Consumer; " + returnedMessage + "\nCorrelationData id = " + dataId);
            } else {
                logger.info("CorrelationData with id " + dataId + " acknowledged;");
            }

        } else {
            if (ack) {
                logger.warn("Unknown message acknowledgement received: " + correlationData);
            } else {
                logger.info("Broker didn't accept message: " + cause);
            }
        }
    }
}

此回调方法 confirm(...) 将在尝试在此类无界队列的交换中发送消息后立即触发 。 在 correlationData 对象中,您会找到 returnedMessage 字段,其中 messagePropertiesbody 您的消息

3。将 RabbitConfirmCallback 设置为 RabbitTemplate

@Autowired
public void post(RabbitTemplate rabbitTemplate, RabbitConfirmCallback rabbitConfirmCallback){
    rabbitTemplate.setConfirmCallback(rabbitConfirmCallback);
}

4。发送消息时,添加 CorrelationDate 对象

有一些唯一标识符

rabbitTemplate.convertAndSend(exchange, routingKey, wrapMessage(message),
                              new CorrelationData(stringId));