目 录CONTENT

文章目录

spring-retry实现重试功能

在水一方
2022-07-09 / 0 评论 / 0 点赞 / 473 阅读 / 1,530 字 / 正在检测是否收录...

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

原理

基于aop来实现的

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

 <dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
 </dependency>

org.aspectj aspectjweaver

步骤

启用重试功能,添加@EnableRetry

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

}

在方法上添加@Retryable

@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方法中有的)
该回调方法与重试方法写在同一个实现类里面

测试

@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();
  }
}

0

评论区