SpringBoot 整合 Spring Retry——优雅实现接口重试
接口调用失败时直接返回错误不是最佳选择有些场景重试一下就成功了。Spring Retry 提供了声明式重试机制。一、引入依赖dependencygroupIdorg.springframework.retry/groupIdartifactIdspring-retry/artifactId/dependencydependencygroupIdorg.aspectj/groupIdartifactIdaspectjweaver/artifactId/dependency二、开启重试SpringBootApplicationEnableRetrypublicclassSeckillApplication{publicstaticvoidmain(String[]args){SpringApplication.run(SeckillApplication.class,args);}}三、使用 RetryableServicepublicclassPaymentService{privatestaticfinalLoggerlogLoggerFactory.getLogger(PaymentService.class);Retryable(value{RemoteAccessException.class,TimeoutException.class},maxAttempts3,backoffBackoff(delay1000,multiplier2))publicbooleanrefund(StringorderNo){log.info(退款请求: {},orderNo);// 调用第三方支付接口returnthirdPartyRefund(orderNo);}Recoverpublicbooleanrecover(RemoteAccessExceptione,StringorderNo){log.error(退款失败记录到异常表: {},orderNo,e);// 记录到失败表人工处理returnfalse;}}四、自定义重试策略ConfigurationpublicclassRetryConfig{BeanpublicRetryTemplateretryTemplate(){RetryTemplatetemplatenewRetryTemplate();// 重试策略最多重试5次间隔递增ExponentialBackOffPolicybackOffnewExponentialBackOffPolicy();backOff.setInitialInterval(1000);backOff.setMultiplier(2);backOff.setMaxInterval(10000);template.setBackOffPolicy(backOff);// 异常判断哪些异常需要重试SimpleRetryPolicyretryPolicynewSimpleRetryPolicy();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(valueOptimisticLockException.class,maxAttempts3,backoffBackoff(delay200))publicbooleandeductStock(LongproductId){// 乐观锁失败时自动重试returnproductMapper.updateStock(productId)0;}} 觉得有用的话点赞 关注【张老师技术栈】吧