前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring-retry实现重试功能

spring-retry实现重试功能

作者头像
在水一方
发布2022-09-07 13:59:01
4450
发布2022-09-07 13:59:01
举报
文章被收录于专栏:在水一方

今天来学习一下spring-retry实现重试功能,在实际项目中这种场景也是比较常见的,如果我们自己用代码实现,但是这种方式侵入性太强,不够优雅

原理

基于aop来实现的

如果找不到注解则自行添加

代码语言:javascript
复制
 <dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
 </dependency>

org.aspectjaspectjweaver

步骤

启用重试功能,添加@EnableRetry

代码语言:javascript
复制
@EnableRetry
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

}

在方法上添加@Retryable

代码语言:javascript
复制
@Service
public class RetryServiceImpl implements RetryService {
    @Override
    @Retryable(value = Exception.class,maxAttempts = 5,backoff = 
    @Backoff(delay = 5000l,multiplier = 1))
    public int demo(int number) throws Exception{
        System.out.println("test被调用");
          if (number==0){
              throw new Exception("抛异常了!");
          }
        System.out.println("test被调用,完成!");
 
        return ResponEntity.success();
    }
}

参数说明

value:抛出指定异常才会重试 include:和value一样,默认为空,当exclude也为空时,默认所有异常 exclude:指定不处理的异常 maxAttempts:最大重试次数,默认3次

@Backoff注解 delay:指定延迟后重试 multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover 当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调

@Recover注意事项

方法的返回值必须与@Retryable方法一致 方法的第一个参数,必须是Throwable类型的,建议是与@Retryable配置的异常一致,其他的参数,需要哪个参数,写进去就可以了(@Recover方法中有的) 该回调方法与重试方法写在同一个实现类里面

测试
代码语言:javascript
复制
@SpringBootApplication
@EnableRetry
public class Application {
  public static void main(String[] args) throws Exception {
    ApplicationContext annotationContext = new AnnotationConfigApplicationContext("hello");
    RemoteService remoteService = annotationContext.getBean("retryService ", RetryService.class);
    retryService.demo();
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 原理
  • 步骤
  • 参数说明
    • @Recover注意事项
      • 测试
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档