springboot2+spring-retry配置及使用

2022年9月27日13:15:48

参考

https://blog.csdn.net/qq877728715/article/details/110039456
https://my.oschina.net/u/4293290/blog/3423913
https://blog.csdn.net/huanongying123/article/details/104417712

1 配置依赖

<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId><version>1.3.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.2.3.RELEASE</version></dependency>

2 启动类开启retry

启动类上添加@EnableRetry注解。

@EnableRetry@SpringBootApplication@MapperScan({"com.test.springbootplus.**.mapper"})publicclassRetryTestApplication{publicstaticvoidmain(String[] args){SpringApplication.run(RetryTestApplication.class, args);}}

3 使用

service层方法类上使用注解,设置retry策略。相关注解如下所示。

@Retryable和@Backoff

注解参数 说明
value 抛出指定异常才会重试
include 和value一样,默认为空,当exclude也为空时,默认所有异常
exclude 指定异常不重试,默认空,当include也为空时,所有异常都重试
maxAttempts 重试次数,默认3
backoff 重试补偿机制,默认使用@Backoff。@Backoff:value:每次重试延迟毫秒数,默认为1000L,和delay一样,在指数级情况下用作初始值delay:重试的间隔时间multiplier:delay时间的间隔倍数,(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试。maxDelay:重试次数之间的最大时间间隔,默认为0,如果小于delay的设置,则默认为30000L

@Recover

用于@Retryable重试失败后处理方法,此注解注释的方法参数一定要是@Retryable抛出的异常(即@Retryable的value值),返回类型也需与@Retryable的方法保持一致,否则无法识别。

使用样例

当抛出Exception异常时,在返回响应之前最多重试3次,每次间隔时间1秒、2秒、3.5秒(本应是4秒,但最大间隔是3.5秒)。重试三次后执行@Recover注解所在方法。

@Retryable(value=Exception.class, maxAttempts=3, backoff=@Backoff(delay=1000, multiplier=2, maxDelay=3500))publicvoidtestRetry()throwsException{
        log.info("---------  进入  ------------");// 这里省略具体的业务逻辑}@Recoverpublicvoidrecover(Exception e){
        log.error("------------  retry重试后回调方法执行 --------------");}
  • 作者:LOOPY_Y
  • 原文链接:https://blog.csdn.net/weixin_46505978/article/details/112504008
    更新时间:2022年9月27日13:15:48 ,共 1626 字。