文章目录
- 一、spring的@Retryable
- 1.1 作用:
- 1.2链接:https://www.cnblogs.com/EasonJim/p/7684649.html
- 1.3 坑
- 1.4 @Recover
- 补充
- 依赖
- 二、Guava-retry:使用
一、spring的@Retryable
1.1 作用:
@Retryable注解,被注解的方法发生异常时会重试
1.2链接:https://www.cnblogs.com/EasonJim/p/7684649.html
@启动类
@EnableRetry
public class ApplicationLoader {}
1.3 坑
https://blog.csdn.net/qq_20989105/article/details/80003087
https://blog.csdn.net/wtopps/article/details/103698635
1、不能内部调用
2、delay = 100(ms)单位是ms,太小的话,比如5ms,相当于失败的瞬间再次调用了,很可能再次失败
3、value = 可重试的异常类型。 include() 的同义词。 默认为空(如果 excludes 也是空的,则重试所有异常)。
1.4 @Recover
1、使用
@Resource
private ProcesstService processtService;@Retryable(recover = "recoverSubmit")public String submit(BillSubmitRequest req) {try {BillSubmitResponse resp = processtService.submit(req);int code = resp.getErrorCode();if (code != 0) {throw new GatewayException(ExceptionCodeConstant.GATEWAY_EXCEPTION_CODE,"创建流程失败,resp:" + GsonUtils.toJsonStr(resp));}return resp.getBillNo();} catch (TException e) {throw new GatewayException(ExceptionCodeConstant.GATEWAY_EXCEPTION_CODE, "创建流程发生异常", e);}}@Recoverpublic String recoverSubmit(Exception e, BillSubmitRequest req) throws Exception {log.error("创建流程异常,req:[{}]", GsonUtils.toJsonStr(req), e);throw e;}
补充
-
默认重试3次
-
任何异常,都等触发重试
-
recover:当重试3次后,会走到对应的recover指定方法中。
如果方法recoverSubmit方法中不throw e,就相当于,吃掉了异常。
- 如果上层,强依赖此submit方法数据,则必须throw e,中断流程
- 如果上层,不强依赖此submit方法数据,则无需throw e。是否throw判断逻辑和原本方法不使用recover一致
依赖
- pom
<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId><version>1.3.4</version>
</dependency>// 由于该组件是依赖于 AOP 给你的,所以还需要引入这个依赖(如果你其他 jar 包中引用过了,当然也就不需要再次引用了)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId><version>2.6.1</version>
</dependency>
- 启动类
@EnableRetry
public class ApplicationStarter {public static void main(String[] args) {SpringApplication.run(ApplicationStarter.class);}
}
- 注意事项
@Recoverpublic String recoverSubmit(Exception e, BillSubmitRequest req) throws Exception {log.error("创建流程异常,req:[{}]", GsonUtils.toJsonStr(req), e);throw e;}
- 补偿方法的参数不是当前异常或者异常的父类,抛出ExhaustedRetryException 异常。所以建议是Exception
- @Recover方法需要和@Retryable方法在同一个类中才能生效@Recover方法(@Recover方法在父类中也可以生效)
二、Guava-retry:使用
https://zzzgd.blog.csdn.net/article/details/84377962?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1.pc_relevant_default&utm_relevant_index=2
场景:生成单据号,通过redis原子自增生成时,需要Guava-retry保证redis的Client执行成功
作用:防止redis超时等