SpringBoot消息重试机制怎么配置?自动重试保证数据一致性的方法
在分布式系统中,网络抖动、服务超时、资源繁忙等问题时有发生。
想象一下:
- 用户下单后,订单消息发送失败,导致库存没有扣减...
- 支付成功后,通知消息丢失,导致订单状态没有更新...
这些问题如果处理不当,很容易造成数据不一致!
今天就带大家深入了解SpringBoot 中的消息重试机制,让失败的消息能够自动重试,保证系统的可靠性!
一、为什么需要重试机制?
1.1 重试机制的作用
重试机制 是指当某个操作失败时,系统自动重新执行该操作的机制。
生活中的例子:
就像你打电话给朋友,第一次没人接,你会再打一次;如果还是没人接,你可能会隔一段时间再打。重试机制就是让系统自动帮我们做这件事。
1.2 需要重试的场景
场景 | 说明 | 重试是否有效 |
| 网络抖动 | 网络瞬间不稳定 | ✅ 有效 |
| 服务超时 | 目标服务响应慢 | ✅ 有效 |
| 资源繁忙 | 数据库连接池满 | ✅ 有效 |
| 业务异常 | 数据校验失败 | ❌ 无效 |
二、SpringBoot 中的重试方式
2.1 方式一:使用 @Retryable 注解
什么是 @Retryable?
这是 Spring Retry 提供的注解,可以轻松实现方法级别的重试。
使用步骤:
第一步:添加依赖
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>第二步:启用重试功能
@SpringBootApplication
@EnableRetry // 启用重试功能
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}第三步:使用 @Retryable 注解
@Service
public class OrderService {
/**
* 处理订单方法
* 当抛出 RuntimeException 时自动重试
*/
@Retryable(
retryFor = RuntimeException.class, // 对哪些异常重试
maxAttempts = 3, // 最大重试次数
backoff = @Backoff( // 退避策略
delay = 1000, // 初始延迟时间(毫秒)
multiplier = 2, // 延迟倍数
maxDelay = 10000 // 最大延迟时间
)
)
public void processOrder(String orderId) {
log.info("处理订单: {}, 时间: {}", orderId, LocalDateTime.now());
// 模拟业务异常
if (new Random().nextBoolean()) {
throw new RuntimeException("网络超时");
}
log.info("订单处理成功: {}", orderId);
}
/**
* 重试失败后的回调方法
*/
@Recover
public void recover(RuntimeException e, String orderId) {
log.error("订单处理最终失败: {}, 原因: {}", orderId, e.getMessage());
// 可以记录到数据库或发送告警
}
}2.2 方式二:手动实现重试逻辑
如果你需要更灵活的控制,可以手动实现重试逻辑:
@Service
public class RetryService {
/**
* 手动重试方法
*/
public <T> T executeWithRetry(Callable<T> task, int maxAttempts, long delayMs) {
int attempt = 0;
Exception lastException = null;
while (attempt < maxAttempts) {
try {
attempt++;
log.info("第 {} 次尝试", attempt);
return task.call();
} catch (Exception e) {
lastException = e;
log.warn("第 {} 次尝试失败: {}", attempt, e.getMessage());
if (attempt < maxAttempts) {
try {
Thread.sleep(delayMs * attempt); // 指数退避
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
}
throw new RuntimeException("重试 " + maxAttempts + " 次后仍然失败", lastException);
}
}
// 使用示例
@Service
public class OrderService {
private final RetryService retryService;
public OrderService(RetryService retryService) {
this.retryService = retryService;
}
public void processOrder(String orderId) {
retryService.executeWithRetry(() -> {
// 业务逻辑
processOrderInternal(orderId);
return null;
}, 3, 1000);
}
}三、Kafka 消费者重试机制
3.1 自动重试配置
在 Kafka 消费者中,可以通过配置实现自动重试:
spring:
kafka:
consumer:
enable-auto-commit: false # 手动提交偏移量
auto-offset-reset: earliest # 失败后从最早开始消费
listener:
ack-mode: manual # 手动确认模式
retry:
max-attempts: 3 # 最大重试次数
initial-interval: 1000 # 初始重试间隔(毫秒)
multiplier: 2 # 间隔倍数
max-interval: 10000 # 最大间隔时间3.2 结合死信队列
当重试多次仍然失败时,可以将消息发送到死信队列:
@Configuration
public class KafkaConfig {
@Bean
public ConcurrentKafkaListenerContainerFactory<String, OrderMessage> kafkaListenerContainerFactory(
ConsumerFactory<String, OrderMessage> consumerFactory,
KafkaTemplate<String, OrderMessage> kafkaTemplate) {
ConcurrentKafkaListenerContainerFactory<String, OrderMessage> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
// 创建死信队列恢复器
DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer(kafkaTemplate);
// 设置错误处理器:重试3次后发送到死信队列
SeekToCurrentErrorHandler errorHandler = new SeekToCurrentErrorHandler(
recoverer,
new FixedBackOff(1000, 3) // 每次重试间隔1秒,最多重试3次
);
factory.setErrorHandler(errorHandler);
return factory;
}
}3.3 自定义重试策略
@Component
public class CustomRetryPolicy implements RetryPolicy {
private static final int MAX_ATTEMPTS = 3;
private static final long MIN_DELAY = 1000;
private static final long MAX_DELAY = 10000;
@Override
public boolean canRetry(RetryContext context) {
return context.getRetryCount() < MAX_ATTEMPTS;
}
@Override
public RetryContext open(RetryContext parent) {
return new DefaultRetryContext(parent);
}
@Override
public void close(RetryContext context) {
// 清理资源
}
}四、重试机制的最佳实践
4.1 指数退避策略
什么是指数退避?
每次重试的间隔时间呈指数增长。
示例:
- 第1次重试:1秒后
- 第2次重试:2秒后(1 × 2)
- 第3次重试:4秒后(2 × 2)
- 第4次重试:8秒后(4 × 2)
优点:
- 避免短时间内大量重试导致系统雪崩
- 给服务足够的时间恢复
4.2 熔断机制
当某个服务持续失败时,应该触发熔断,停止重试:
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreaker circuitBreaker() {
return CircuitBreaker.builder()
.failureThreshold(50) // 失败率超过50%触发熔断
.waitDurationInOpenState(Duration.ofSeconds(30)) // 熔断30秒
.build();
}
}4.3 区分可重试和不可重试异常
@Retryable(
retryFor = {NetworkException.class, TimeoutException.class}, // 可重试异常
exclude = {IllegalArgumentException.class} // 不可重试异常
)
public void processOrder(String orderId) {
// 业务逻辑
}4.4 记录重试日志
@Retryable(
retryFor = RuntimeException.class,
maxAttempts = 3
)
public void processOrder(String orderId) {
log.info("开始处理订单: {}", orderId);
// 业务逻辑
log.info("订单处理成功: {}", orderId);
}
@Recover
public void recover(RuntimeException e, String orderId) {
log.error("订单处理最终失败,已重试3次: {}, 原因: {}", orderId, e.getMessage());
// 记录到数据库
retryLogRepository.save(new RetryLog(orderId, e.getMessage()));
// 发送告警通知
alertService.sendAlert("订单处理失败", orderId);
}五、完整示例:订单重试服务
@Service
public class OrderRetryService {
private static final int MAX_RETRY = 3;
private static final long INITIAL_DELAY = 1000;
private final RestTemplate restTemplate;
private final OrderRepository orderRepository;
public OrderRetryService(RestTemplate restTemplate, OrderRepository orderRepository) {
this.restTemplate = restTemplate;
this.orderRepository = orderRepository;
}
/**
* 通知库存服务扣减库存
*/
public void notifyInventory(String orderId) {
String url = "http://inventory-service/api/inventory/deduct";
retryWithExponentialBackoff(() -> {
ResponseEntity<String> response = restTemplate.postForEntity(
url,
new InventoryRequest(orderId),
String.class
);
if (!response.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("库存服务返回失败: " + response.getStatusCode());
}
log.info("库存扣减成功: {}", orderId);
}, MAX_RETRY, INITIAL_DELAY);
}
/**
* 指数退避重试方法
*/
private void retryWithExponentialBackoff(Runnable task, int maxAttempts, long initialDelay) {
int attempts = 0;
long delay = initialDelay;
while (attempts < maxAttempts) {
try {
attempts++;
task.run();
return; // 成功则返回
} catch (Exception e) {
log.warn("第 {} 次尝试失败: {}", attempts, e.getMessage());
if (attempts < maxAttempts) {
try {
log.info("等待 {} 毫秒后重试", delay);
Thread.sleep(delay);
delay *= 2; // 指数增长
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("重试被中断", ie);
}
}
}
}
// 所有重试都失败
log.error("已重试 {} 次,任务仍然失败", maxAttempts);
throw new RuntimeException("任务重试失败");
}
}总结
今天的内容就到这里啦!
通过这篇文章,我们一起学习了:
- 1. ✅ 为什么需要重试机制
- 2. ✅ SpringBoot 中的重试方式(@Retryable 注解)
- 3. ✅ 手动实现重试逻辑
- 4. ✅ Kafka 消费者的重试配置
- 5. ✅ 重试机制的最佳实践(指数退避、熔断、异常区分)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
springboot 运行 jar 包读取外部配置文件的问题
这篇文章主要介绍了springboot 运行 jar 包读取外部配置文件,本文主要描述linux系统执行jar包读取jar包同级目录的外部配置文件,主要分为两种方法,每种方法通过实例代码介绍的非常详细,需要的朋友可以参考下2021-07-07
SpringBoot集成Knife4j实现接口文档和参数校验
Knife4j 是国人开发的接口文档增强工具,底层基于 OpenAPI 规范,但提供了比原生 Swagger UI 更美观、更贴合国内开发者习惯的中文界面,本文就给大家介绍了SpringBoot集成Knife4j实现接口文档和参数校操作步骤,需要的朋友可以参考下2026-03-03
RabbitMQ中Confirm消息确认机制保障生产端消息的可靠性详解
这篇文章主要介绍了RabbitMQ中Confirm消息确认机制保障生产端消息的可靠性详解,生产者将数据发送到 RabbitMQ 的时候,可能数据就在半路给搞丢了,因为网络问题啥的,都有可能,需要的朋友可以参考下2023-12-12
Spring Boot中使用jdbctemplate 操作MYSQL数据库实例
本篇文章主要介绍了Spring Boot中使用jdbctemplate 操作MYSQL数据库实例,具有一定的参考价值,有兴趣的可以了解一下。2017-04-04


最新评论