在分布式系统中,网络抖动、服务超时、资源繁忙等问题时有发生。
想象一下:
- 用户下单后,订单消息发送失败,导致库存没有扣减...
- 支付成功后,通知消息丢失,导致订单状态没有更新...
这些问题如果处理不当,很容易造成数据不一致!
今天就带大家深入了解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. ✅ 重试机制的最佳实践(指数退避、熔断、异常区分)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论