SpringBoot @Retryable注解方式

 更新时间:2020年09月18日 10:16:16   作者:wtopps  
这篇文章主要介绍了SpringBoot @Retryable注解方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

背景

在调用第三方接口或者使用MQ时,会出现网络抖动,连接超时等网络异常,所以需要重试。为了使处理更加健壮并且不太容易出现故障,后续的尝试操作,有时候会帮助失败的操作最后执行成功。一般情况下,需要我们自行实现重试机制,一般是在业务代码中加入一层循环,如果失败后,再尝试重试,但是这样实现并不优雅。在SpringBoot中,已经实现了相关的能力,通过@Retryable注解可以实现我们想要的结果。

@Retryable

首先来看一下Spring官方文档的解释:

@Retryable注解可以注解于方法上,来实现方法的重试机制。

POM依赖

<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.springframework.boot</groupId>
 <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

使用实例

SpringBoot retry的机制比较简单,只需要两个注解即可实现。

启动类

@SpringBootApplication
@EnableRetry
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
}

在启动类上,需要加入@EnableRetry注解,来开启重试机制。

Service类

前面提到过,@Retryable是基于方法级别的,因此在Service中,需要在你希望重试的方法上,增加重试注解。

@Service
@Slf4j
public class DoRetryService {

 @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
 public boolean doRetry(boolean isRetry) throws Exception {
  log.info("开始通知下游系统");
  log.info("通知下游系统");
  if (isRetry) {
   throw new RuntimeException("通知下游系统异常");
  }
  return true;
 }
}

来简单解释一下注解中几个参数的含义:

名称 含义
interceptor Retry interceptor bean name to be applied for retryable method.
value Exception types that are retryable. Synonym for includes(). Defaults to empty (and if excludes is also empty all exceptions are retried).
include Exception types that are retryable. Defaults to empty (and if excludes is also empty all exceptions are retried).
exclude Exception types that are not retryable. Defaults to empty (and if includes is also empty all exceptions are retried).
label A unique label for statistics reporting. If not provided the caller may choose to ignore it, or provide a default.
stateful Flag to say that the retry is stateful: i.e. exceptions are re-thrown, but the retry policy is applied with the same policy to subsequent invocations with the same arguments. If false then retryable exceptions are not re-thrown.
maxAttempts the maximum number of attempts (including the first failure), defaults to 3
maxAttemptsExpression an expression evaluated to the maximum number of attempts (including the first failure), defaults to 3
backoff Specify the backoff properties for retrying this operation. The default is a simple specification with no properties.
exceptionExpression Specify an expression to be evaluated after the SimpleRetryPolicy.canRetry() returns true - can be used to conditionally suppress the retry.
listeners Bean names of retry listeners to use instead of default ones defined in Spring context.

上面是@Retryable的参数列表,参数较多,这里就选择几个主要的来说明一下:

interceptor:可以通过该参数,指定方法拦截器的bean名称

value:抛出指定异常才会重试

include:和value一样,默认为空,当exclude也为空时,默认所以异常

exclude:指定不处理的异常

maxAttempts:最大重试次数,默认3次

backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000L;multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为3秒,第三次为4.5秒。

我们把上面的例子执行一下,来看看效果:

2019-12-25 11:38:02.492 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 开始通知下游系统
2019-12-25 11:38:02.493 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 通知下游系统
2019-12-25 11:38:04.494 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 开始通知下游系统
2019-12-25 11:38:04.495 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 通知下游系统
2019-12-25 11:38:07.496 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 开始通知下游系统
2019-12-25 11:38:07.496 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 通知下游系统
2019-12-25 11:38:11.997 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 开始通知下游系统
2019-12-25 11:38:11.997 INFO 25664 --- [   main] c.f.l.service.impl.DoRetryServiceImpl : 通知下游系统

java.lang.RuntimeException: 通知下游系统异常
...
...
...

可以看到,三次之后抛出了RuntimeException的异常。

@Recover

当重试耗尽时,RetryOperations可以将控制传递给另一个回调,即RecoveryCallback。Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法,此方法里的异常一定要是@Retryable方法里抛出的异常,否则不会调用这个方法。

@Recover

public boolean doRecover(Throwable e, boolean isRetry) throws ArithmeticException {
 log.info("全部重试失败,执行doRecover");
 return false;
}

对于@Recover注解的方法,需要特别注意的是:

1、方法的返回值必须与@Retryable方法一致

2、方法的第一个参数,必须是Throwable类型的,建议是与@Retryable配置的异常一致,其他的参数,需要与@Retryable方法的参数一致

/**
 * Annotation for a method invocation that is a recovery handler. A suitable recovery
 * handler has a first parameter of type Throwable (or a subtype of Throwable) and a
 * return value of the same type as the <code>@Retryable</code> method to recover from.
 * The Throwable first argument is optional (but a method without it will only be called
 * if no others match). Subsequent arguments are populated from the argument list of the
 * failed method in order.
 */

@Recover不生效的问题

在测试过程中,发现@Recover无法生效,执行时抛出异常信息:

org.springframework.retry.ExhaustedRetryException: Cannot locate recovery method; nested exception is java.lang.ArithmeticException: / by zero

at org.springframework.retry.annotation.RecoverAnnotationRecoveryHandler.recover(RecoverAnnotationRecoveryHandler.java:61)
at org.springframework.retry.interceptor.RetryOperationsInterceptor$ItemRecovererCallback.recover(RetryOperationsInterceptor.java:141)
at org.springframework.retry.support.RetryTemplate.handleRetryExhausted(RetryTemplate.java:512)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:351)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:180)
at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:115)
at org.springframework.retry.annotation.AnnotationAwareRetryOperationsInterceptor.invoke(AnnotationAwareRetryOperationsInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy157.doRetry(Unknown Source)

追踪一下异常的信息,进入到RecoverAnnotationRecoveryHandler中,找到报错的方法public T recover(Object[] args, Throwable cause),看一下其实现:

发现报错处,是因为method为空而导致的,明明我已经在需要执行的方法上注解了@Recover,为什么还会找不到方法呢?很奇怪,再来深入追踪一下:

打断点到这,发现methods列表是空的,那么methods列表是什么时候初始化的呢?继续追踪:

发现了初始化methods列表的地方,这里会扫描注解了@Recover注解的方法,将其加入到methds列表中,那么为什么没有扫描到我们注解了的方法呢?

很奇怪,为什么明明注解了@Recover,这里却没有扫描到呢?

我有点怀疑Spring扫描的部分,可能有什么问题了,回头去看看@EnableRetry是怎么说的:

终于找到问题的所在了,对于@EnableRetry中的proxyTargetClass参数,是控制是否对使用接口实现的bean开启代理类,默认的情况下,是不开启的,问题原因就是这个,我们来实验一下,把这个参数改成true:

@EnableRetry(proxyTargetClass = true)

再次运行,果然没有问题了。

由此得出结论,当使用接口实现的bean时,需要将EnableRetry的参数改为true,非接口的实现,可以使用默认配置,即false。

结语

本篇主要简单介绍了Springboot中的Retryable的使用,主要的适用场景为在调用第三方接口或者使用MQ时。由于会出现网络抖动,连接超时等网络异常。

以上这篇SpringBoot @Retryable注解方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 一篇文章弄懂JVM类加载机制过程以及原理

    一篇文章弄懂JVM类加载机制过程以及原理

    JVM原理对于初学者而言,比较晦涩难以理解,概念繁多又比较抽象,很多时候感觉看不见摸不着,还不好验证,下面这篇文章主要给大家介绍了关于如何通过一篇文章弄懂JVM类加载机制过程及原理的相关资料,需要的朋友可以参考下
    2023-02-02
  • spring boot 中设置默认网页的方法

    spring boot 中设置默认网页的方法

    这篇文章主要介绍了spring boot 中设置默认网页的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • 使用SpringAOP实现公共字段填充功能

    使用SpringAOP实现公共字段填充功能

    在新增员工或者新增菜品分类时需要设置创建时间、创建人、修改时间、修改人等字段,在编辑员工或者编辑菜品分类时需要设置修改时间、修改人等字段,这些字段属于公共字段,本文将给大家介绍使用SpringAOP实现公共字段填充功能,需要的朋友可以参考下
    2024-08-08
  • SpringBoot的ConfigurationProperties或Value注解无效问题及解决

    SpringBoot的ConfigurationProperties或Value注解无效问题及解决

    在SpringBoot项目开发中,全局静态配置类读取application.yml或application.properties文件时,可能会遇到配置值始终为null的问题,这通常是因为在创建静态属性后,IDE自动生成的Get/Set方法包含了static关键字
    2024-11-11
  • vue3使用vue-diff工具来比较数据差异

    vue3使用vue-diff工具来比较数据差异

    这篇文章主要为大家详细介绍了vue3如何使用vue-diff工具来比较数据差异,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-11-11
  • spring boot动态切换数据源的实现

    spring boot动态切换数据源的实现

    这篇文章主要介绍了spring boot动态切换数据源的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Java后台接收数据的三种方式(url、form-data与application/json)

    Java后台接收数据的三种方式(url、form-data与application/json)

    本文主要介绍了Java后台接收数据的三种方式(url、form-data与application/json),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • Java基础详解之内存泄漏

    Java基础详解之内存泄漏

    这篇文章主要介绍了Java基础详解之内存泄漏,文中有非常详细的代码示例,对正在学习java的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-04-04
  • map实现按value升序排序

    map实现按value升序排序

    map内部是按照hash算法存储的,但如果能对map排序在某些时候还是有用的,下面实现对map按照value升序排序,实现对map按照key排序,大家参考使用吧
    2014-01-01
  • SpringBoot AOP注解失效问题排查与解决(调用内部方法)

    SpringBoot AOP注解失效问题排查与解决(调用内部方法)

    这篇文章主要介绍了SpringBoot AOP注解失效问题排查与解决(调用内部方法),文中通过代码示例介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-04-04

最新评论