SpringBoot 整合 Spring Retry——优雅实现接口重试
📅 2026/7/30 19:43:13
👁️ 阅读次数
📝 编程学习
接口调用失败时,直接返回错误不是最佳选择,有些场景重试一下就成功了。Spring Retry 提供了声明式重试机制。
一、引入依赖
<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency>二、开启重试
@SpringBootApplication@EnableRetrypublicclassSeckillApplication{publicstaticvoidmain(String[]args){SpringApplication.run(SeckillApplication.class,args);}}三、使用 @Retryable
@ServicepublicclassPaymentService{privatestaticfinalLoggerlog=LoggerFactory.getLogger(PaymentService.class);@Retryable(value={RemoteAccessException.class,TimeoutException.class},maxAttempts=3,backoff=@Backoff(delay=1000,multiplier=2))publicbooleanrefund(StringorderNo){log.info("退款请求: {}",orderNo);// 调用第三方支付接口returnthirdPartyRefund(orderNo);}@Recoverpublicbooleanrecover(RemoteAccessExceptione,StringorderNo){log.error("退款失败,记录到异常表: {}",orderNo,e);// 记录到失败表,人工处理returnfalse;}}四、自定义重试策略
@ConfigurationpublicclassRetryConfig{@BeanpublicRetryTemplateretryTemplate(){RetryTemplatetemplate=newRetryTemplate();// 重试策略:最多重试5次,间隔递增ExponentialBackOffPolicybackOff=newExponentialBackOffPolicy();backOff.setInitialInterval(1000);backOff.setMultiplier(2);backOff.setMaxInterval(10000);template.setBackOffPolicy(backOff);// 异常判断:哪些异常需要重试SimpleRetryPolicyretryPolicy=newSimpleRetryPolicy();retryPolicy.setMaxAttempts(5);template.setRetryPolicy(retryPolicy);returntemplate;}}五、编程式重试
@ServicepublicclassOrderService{@AutowiredprivateRetryTemplateretryTemplate;publicbooleanprocessOrder(LongorderId){returnretryTemplate.execute(context->{log.info("处理订单,第{}次尝试",context.getRetryCount()+1);returndoProcess(orderId);},context->{log.error("最终失败",context.getLastThrowable());returnfalse;});}}六、重试配置
spring:retry:max-attempts:3# 全局最大重试次数七、秒杀系统应用
@ServicepublicclassSeckillService{@Retryable(value=OptimisticLockException.class,maxAttempts=3,backoff=@Backoff(delay=200))publicbooleandeductStock(LongproductId){// 乐观锁失败时自动重试returnproductMapper.updateStock(productId)>0;}}💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!
编程学习
技术分享
实战经验