spring boot 全局异常处理无法直接捕获消息丢失异常,因为这类异常通常发生在消息发送阶段而非业务逻辑中。要解决此问题,需为 rabbittemplate 配置 mandatory 回调和 returncallback,在发送端拦截返回的 nackedmessage 或 returnedmessage 对象,从而获取具体的错误原因并记录日志。

如何配置 RabbitTemplate 以接收未路由消息?
通过实现 RabbitTemplate.ReturnCallback 接口并重写 returnedMessage 方法,可以捕获因队列不存在或路由键不匹配而导致的消息退回。在此方法中,提取 message、replyCode 和 replyText 进行统一处理。

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
// 关键配置:设置为 true 以触发 ReturnCallback
template.setMandatory(true);
template.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
System.out.println("消息丢失: " + message.getMessageProperties().getMsgId());
System.out.println("原因: " + replyText);
});
return template;
}
}
如何确保消息到达交换机后不被丢弃?
除了监听退回消息,还需在消费者端配置 acknowledge-mode 为手动模式,并在消费失败时调用 nack 方法将消息重新入队或转入死信队列,防止因处理异常导致消息静默丢失。

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class MessageConsumer {
@RabbitListener(queues = "my_queue")
public void handle(String body, Channel channel, Message message) throws Exception {
try {
// 业务逻辑处理
process(body);
// 确认消费成功
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
// 拒绝消息并重新入队
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
}
}
}
当 Exchange 类型设为 Direct 且无匹配 Queue 时会发生什么?
如果 Exchange 类型为 Direct 且没有 Queue 绑定到该 Routing Key,消息会被交换机丢弃。由于配置了 setMandatory(true),交换机会立即向生产者发送一个 NACK 响应,触发之前注册的 ReturnCallback,此时 replyCode 将为 312(NO_ROUTE),replyText 包含 "No route" 信息,开发者可据此判断是路由配置错误。











