【RabbitMQ】Rabbitmq如何保证消息不回丢失? - 次重试失败"
rabbitmq如何保证消息不会丢失?
1.queue和交换机的持久化
2.发送消息的持久化
3.消费者确认机制
queue和交换机的持久化
这个问题实际上问的是消息从 生产者-》exchange-〉queue,queue是如何保证消息能够接收到消息,做到不丢失消息的?
RabbitMQ默认接收到消息,不会立刻持久化,而是保存到内存到中去,如果不巧的是mq此时挂了,那么此时消息就会丢失。所以就需要持久化来让消息保存到磁盘中。
真实项目中,核心业务队列的 exclusive 必须为 false,以支持多实例、持久化和跨服务访问;exclusive = true 仅用于临时、单连接专属的边缘场景。
当durable设置为true时,那么通常队列与交换机保存持久化关系。在服务重启后,绑定关系不会丢失。
发送消息的持久化
生产者发送消息的时候也可以为消息设定deliveryMode=2来设定消息的持久化
deliveryMode 有两个常用取值,分别对应不同的消息持久化策略:
deliveryMode = 1:表示消息为非持久化(transient)这类消息仅存储在 RabbitMQ 服务器的内存中,不写入磁盘。如果 RabbitMQ 服务重启(或崩溃),消息会直接丢失。适用于临时性、可丢失的消息(如实时监控数据、非关键通知),优势是性能开销小(无磁盘 IO 操作)。
deliveryMode = 2:表示消息为持久化(persistent)这类消息会被 RabbitMQ 写入磁盘(具体存储位置依赖配置),即使服务重启,消息也能从磁盘恢复。适用于关键业务消息(如订单数据、支付通知),需保证消息不丢失,但会增加磁盘 IO 开销,可能影响吞吐量。
每个发送方法单独配置(优先级更高,也推荐使用)
public void sendPersistentMessage(String exchange, String routingKey, String message) {
// 发送持久化消息(deliveryMode = 2)
rabbitTemplate.convertAndSend(
exchange,
routingKey,
message,
// 匿名内部类实现 MessagePostProcessor,修改消息属性
new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) {
// 设置 deliveryMode 为持久化
message.getMessageProperties().setDeliveryMode(DeliveryMode.PERSISTENT);
return message;
}
}
);
}
全局配置
@Configuration
public class RabbitConfig {
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
// 设置自定义消息转换器,全局默认持久化
rabbitTemplate.setMessageConverter(new AbstractMessageConverter() {
@Override
protected Message createMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
// 设置默认 deliveryMode 为持久化
messageProperties.setDeliveryMode(DeliveryMode.PERSISTENT);
// 序列化消息体(这里以字符串为例,实际可根据需求用 Jackson 等)
byte[] body = object.toString().getBytes();
return new Message(body, messageProperties);
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
// 消息接收时的反序列化逻辑(根据业务实现)
return new String(message.getBody());
}
});
return rabbitTemplate;
}
}
消费者的确认机制
一般默认的设置都是自动ack确认消息,然后消费。但是这样如果出错了的话,系统并不会处理这种错误补偿,人工也比较难第一时间感知到。
所以需要将自动ack改为手动ack的方式,消息再没有ack的时候,可以再次投递到本queue中再次消费,避免丢失。
核心原理
当 RabbitMQ 将消息投递给消费者后,不会立即将消息从队列中删除,而是等待消费者发送确认信号(Acknowledgement)。根据确认信号的类型,RabbitMQ 会执行不同操作:
收到确认信号(Ack):认为消息已被正确处理,从队列中删除消息。收到拒绝信号(Nack/Reject):认为消息处理失败,根据配置决定将消息重新入队(requeue)或丢弃(若队列绑定了死信交换机,则可能进入死信队列)。
1. 自动ack(Auto Acknowledgement)
机制:RabbitMQ 将消息投递给消费者后,立即认为消息已处理完成,自动删除消息(无需消费者手动发送确认)。参数:原生客户端 basicConsume 时 autoAck = true;Spring AMQP 中 ackMode = AckMode.NONE。适用场景:消息处理极快且不会失败(如日志收集),或允许消息丢失的场景。风险:若消费者在处理消息过程中崩溃(消息未处理完),消息已被删除,导致丢失。
2. 手动确认(Manual Acknowledgement)
机制:消费者处理完消息后,必须主动发送确认信号(Ack/Nack/Reject),RabbitMQ 才会处理消息。
参数:原生客户端 autoAck = false;Spring AMQP 中 ackMode = AckMode.MANUAL。
核心操作:
Ack(确认):channel.basicAck(deliveryTag, multiple)
deliveryTag:消息的唯一标识(每个消息在信道内有唯一 tag)。multiple:true 表示确认所有 deliveryTag 小于当前值的消息(批量确认)。作用:通知 RabbitMQ 消息已处理,删除消息。
Nack(否定确认):channel.basicNack(deliveryTag, multiple, requeue)
requeue:true 表示消息重新入队,等待再次投递;false 表示丢弃(或进入死信队列)。特点:支持批量操作(multiple = true)。
Reject(拒绝):channel.basicReject(deliveryTag, requeue)
功能与 Nack 类似,但不支持批量操作(multiple 参数不存在)。
适用场景:关键业务消息(如订单、支付),需确保消息处理完成后再删除,失败时可重试。
// 监听队列,指定确认模式为手动
@RabbitListener(queues = "manual.queue", ackMode = "MANUAL")
public void handleMessage(String content, Channel channel, Message message) throws Exception {
try {
// 处理消息(如业务逻辑)
System.out.println("处理消息:" + content);
// 处理成功,发送 Ack 确认(单条确认)
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
// 处理失败,发送 Nack,消息重新入队(requeue = true)
channel.basicNack(
message.getMessageProperties().getDeliveryTag(),
false, // 不批量确认
true // 重新入队
);
// 或使用 reject(不支持批量)
// channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
}
}
3. 自动确认(AckMode.AUTO,Spring 扩展)
这种情况,我不太能够理解所在的业务场景,觉得比较鸡肋。暂时也搁置在这里。
以上三点能够保证持久化,但是存在一个问题,就是万一有一个消息在消费者这里消费失败了,NAck,继续返回了,如果没有特殊处理,此时就会进入死循环。系统慢慢就会被拖垮。
所以还需要结合死信队列(DLX) 和重试次数限制(如通过 RetryTemplate)处理。
1.配置死信队列与交换机
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitDlqConfig {
// 死信交换机(类型:direct)
@Bean
public DirectExchange dlxExchange() {
return ExchangeBuilder.directExchange("dlx.exchange").durable(true).build();
}
// 死信队列(存储超过重试次数的失败消息)
@Bean
public Queue dlqQueue() {
return QueueBuilder.durable("dlq.queue").build();
}
// 死信队列与死信交换机绑定(路由键:dlq.key)
@Bean
public Binding dlqBinding() {
return BindingBuilder.bind(dlqQueue()).to(dlxExchange()).with("dlq.key");
}
// 业务队列(需绑定死信配置)
@Bean
public Queue businessQueue() {
return QueueBuilder.durable("business.queue")
// 指定死信交换机:消息被拒绝且不重新入队时,路由到该交换机
.withArgument("x-dead-letter-exchange", "dlx.exchange")
// 指定死信路由键:死信消息将通过该路由键转发到死信队列
.withArgument("x-dead-letter-routing-key", "dlq.key")
// 可选:设置队列最大长度(满了之后消息也会进入死信)
// .withArgument("x-max-length", 1000)
.build();
}
// 业务交换机(绑定业务队列)
@Bean
public DirectExchange businessExchange() {
return ExchangeBuilder.directExchange("business.exchange").durable(true).build();
}
// 业务队列与业务交换机绑定(路由键:business.key)
@Bean
public Binding businessBinding() {
return BindingBuilder.bind(businessQueue()).to(businessExchange()).with("business.key");
}
}
2.手动实现ack
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
public class ManualAckWithDlqConsumer {
// 最大重试次数(超过则进入死信队列)
private static final int MAX_RETRY_COUNT = 3;
@RabbitListener(queues = "business.queue", ackMode = "MANUAL") // 手动确认模式
public void handleMessage(String messageContent, Channel channel, Message message) throws IOException {
// 获取消息属性中的 headers(用于存储重试次数)
Mapheaders = message.getMessageProperties().getHeaders();
// 读取当前重试次数(首次失败时默认为0)
int retryCount = headers.get("retryCount") == null ? 0 : (Integer) headers.get("retryCount");
try {
// 模拟业务处理(如数据库操作、API调用等)
System.out.println("处理消息:" + messageContent + ",当前重试次数:" + retryCount);
// 模拟处理失败(实际场景中根据业务逻辑判断)
if (true) { // 这里故意抛出异常,模拟处理失败
throw new RuntimeException("处理失败,需要重试");
}
// 处理成功:手动 ACK,消息从队列删除
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
retryCount++; // 重试次数+1
System.out.println("消息处理失败,重试次数更新为:" + retryCount);
if (retryCount >= MAX_RETRY_COUNT) {
// 超过最大重试次数:Nack 且不重新入队(requeue=false),消息进入死信队列
System.out.println("超过最大重试次数(" + MAX_RETRY_COUNT + "),消息将进入死信队列");
channel.basicNack(
message.getMessageProperties().getDeliveryTag(),
false, // 不批量处理
false // 不重新入队(触发死信) 拼多多帮助力入口
);
} else {
// 未超过最大次数:更新重试次数到 headers,Nack 并重新入队(requeue=true)
headers.put("retryCount", retryCount);
message.getMessageProperties().setHeaders(headers); // 更新消息属性
System.out.println("消息将重新入队,等待下次处理");
channel.basicNack(
message.getMessageProperties().getDeliveryTag(),
false, // 不批量处理
true // 重新入队(继续重试)
);
}
}
}
}
注意basicNack的requeue参数决定了是否消息是否重新扔回队列重试,还是扔到死信队列
true:重新入队,继续重试
false:触发死信队列
public void basicNack(long deliveryTag, boolean multiple, boolean requeue) throws IOException {
this.delegate.basicNack(deliveryTag, multiple, requeue);
}
当然还有RetryTemplate不扔回队列的重试方式,基于spring提供的本地方法。
org.springframework.retry
spring-retry
org.springframework.boot
spring-boot-starter-amqp
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryListener;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.retry.backoff.FixedBackOffPolicy;
@Configuration
public class RetryConfig {
// 最大重试次数(含首次尝试,共 3+1=4 次执行)
private static final int MAX_RETRIES = 3;
// 重试间隔(毫秒)
private static final long BACKOFF_PERIOD = 1000;
@Bean
public RetryTemplate retryTemplate() {
// 1. 重试策略:固定次数重试
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(MAX_RETRIES);
// 2. 回退策略:固定间隔重试
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(BACKOFF_PERIOD); // 每次重试间隔 1 秒
// 3. 配置 RetryTemplate
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);
// 可选:添加重试监听器(记录重试日志)
retryTemplate.registerListener(new RetryListener() {
@Override
publicboolean open(RetryContext context, RetryCallbackcallback) {
return true;
}
@Override
publicvoid close(RetryContext context, RetryCallbackcallback, Throwable throwable) {
if (throwable != null) {
System.out.println("重试结束,最终失败:" + throwable.getMessage());
}
}
@Override
publicvoid onError(RetryContext context, RetryCallbackcallback, Throwable throwable) {
System.out.println("第 " + context.getRetryCount() + " 次重试失败");
}
});
return retryTemplate;
}
}
手动的ack结合RetryTemplate
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class RetryTemplateWithManualAckConsumer {
@Autowired
private RetryTemplate retryTemplate;
@RabbitListener(queues = "business.queue", ackMode = "MANUAL") // 手动 ACK 模式
public void handleMessage(String messageContent, Channel channel, Message message) throws IOException {
try {
// 用 RetryTemplate 执行业务逻辑,自动重试
retryTemplate.execute(context ->{
// 业务处理逻辑(如数据库操作、API调用)
System.out.println("处理消息:" + messageContent + ",当前重试次数(本地):" + context.getRetryCount());
// 模拟业务失败(实际场景中根据业务判断)
if (true) {
throw new RuntimeException("业务处理失败,触发重试");
}
return null; // 处理成功返回结果(无返回值时为 null)
});
// 若 RetryTemplate 执行成功(无异常),手动 ACK 确认消息
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
System.out.println("消息处理成功,已 ACK");
} catch (Exception e) {
// RetryTemplate 重试耗尽后仍失败:手动 Nack 且不重新入队,消息进入死信队列
System.out.println("本地重试耗尽,消息将进入死信队列:" + e.getMessage());
channel.basicNack(
message.getMessageProperties().getDeliveryTag(),
false, // 不批量处理
false // 不重新入队(触发死信)
);
}
}
}
RetryTemplate本身就是Spring提供的重试机制,与本文相关的ack并无太大关系。只是想到了这个方法,便写下来记录一下
批量确认(multiple = true)可减少网络交互,提高性能,但需确保批量内的所有消息都已处理完成,否则可能导致未处理的消息被误删除。