提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、引入依赖
- 二、主启动类上加@EnableRetry
- 三、Server层
- 注意
- 四、失败后回调方法
- 总结
前言
提示:SpringBoot项目为例
原文链接:https://blog.csdn.net/imVainiycos/article/details/123106451
一、引入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency>
</dependencies>
二、主启动类上加@EnableRetry
@EnableRetry
@SpringBootApplication
public class KafkaApiApplication {public static void main(String[] args) {SpringApplication.run(KafkaApiApplication.class, args);}
}
三、Server层
注意
定义Controller层:下层需要进行throws抛出异常,或者我们进行try,catch;进行异常捕捉,
否则重试机制将会不生效。
@Retryable()注解中参数说明:
value:哪种异常情况下需要重试.
maxAttempts:最大重试次数
delay:重试延迟时间(毫秒计数)
multiplier:下次执行时间 =上次时间 * 倍数。
/*** 调用第三方接口,方法位置,添加重试注解,相关参数配置。*/@Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 5 * 60 * 1000,multiplier = 2))@Overridepublic void updateBatchOld(List<String> snList) {if (CollectionUtils.isNotEmpty(snList)) {List<DeviceDetailLowFrequency> ktdData = null;try {ktdData = inverterKtdFeign.getKtdData(snList);} catch (Exception e) {log.info("调用低频接口失败:"+ snList);throw new MyException(ResultCodeEnum.FEIGN_SERVICE_ERROR);}ktdData.forEach(a -> a.setUpdateTime(new Date()));this.updateBatchById(ktdData);}}
四、失败后回调方法
若在最大重试次数下,还是没有成功,则回调方法编写。
Service实现类中,代码如下:
/*** 使用 @Recover注解*/@Recoverpublic void recover(Exception e){//记日志到数据库 或 打印日志.}
引用原文链接:点击跳转
总结
提示:好小子,你又在学习,打死你。