接口调用失败时,直接返回错误不是最佳选择,有些场景重试一下就成功了。spring retry 提供了声明式重试机制。
一、引入依赖
<dependency>
<groupid>org.springframework.retry</groupid>
<artifactid>spring-retry</artifactid>
</dependency>
<dependency>
<groupid>org.aspectj</groupid>
<artifactid>aspectjweaver</artifactid>
</dependency>二、开启重试
@springbootapplication
@enableretry
public class seckillapplication {
public static void main(string[] args) {
springapplication.run(seckillapplication.class, args);
}
}
三、使用 @retryable
@service
public class paymentservice {
private static final logger log = loggerfactory.getlogger(paymentservice.class);
@retryable(
value = {remoteaccessexception.class, timeoutexception.class},
maxattempts = 3,
backoff = @backoff(delay = 1000, multiplier = 2)
)
public boolean refund(string orderno) {
log.info("退款请求: {}", orderno);
// 调用第三方支付接口
return thirdpartyrefund(orderno);
}
@recover
public boolean recover(remoteaccessexception e, string orderno) {
log.error("退款失败,记录到异常表: {}", orderno, e);
// 记录到失败表,人工处理
return false;
}
}
四、自定义重试策略
@configuration
public class retryconfig {
@bean
public retrytemplate retrytemplate() {
retrytemplate template = new retrytemplate();
// 重试策略:最多重试5次,间隔递增
exponentialbackoffpolicy backoff = new exponentialbackoffpolicy();
backoff.setinitialinterval(1000);
backoff.setmultiplier(2);
backoff.setmaxinterval(10000);
template.setbackoffpolicy(backoff);
// 异常判断:哪些异常需要重试
simpleretrypolicy retrypolicy = new simpleretrypolicy();
retrypolicy.setmaxattempts(5);
template.setretrypolicy(retrypolicy);
return template;
}
}
五、编程式重试
@service
public class orderservice {
@autowired
private retrytemplate retrytemplate;
public boolean processorder(long orderid) {
return retrytemplate.execute(context -> {
log.info("处理订单,第{}次尝试", context.getretrycount() + 1);
return doprocess(orderid);
}, context -> {
log.error("最终失败", context.getlastthrowable());
return false;
});
}
}
六、重试配置
spring:
retry:
max-attempts: 3 # 全局最大重试次数
七、秒杀系统应用
@service
public class seckillservice {
@retryable(
value = optimisticlockexception.class,
maxattempts = 3,
backoff = @backoff(delay = 200)
)
public boolean deductstock(long productid) {
// 乐观锁失败时自动重试
return productmapper.updatestock(productid) > 0;
}
}
到此这篇关于springboot整合spring retry优雅实现接口重试的示例代码的文章就介绍到这了,更多相关springboot spring retry接口重试内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论