重试机制Retry的使用

 

场景

当项目中调用某个接口或者方法遇到第三方网络异常或者响应异常,希望最多/最少且间隔多久调用几次的需求时,可以使用Retry重试框架。

SpringBoot 实现重试机制

pom.xml

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

启动类添加注解@EnableRetry

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

在需要重试的方法上添加注解

public class RetryDemo {
  
  public int count = 0;
  public long t = 0;

  @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000 * 2, multiplier = 1.5))
  public void TestRetry(String id) {
    count++;
    Long s  = System.currentTimeMillis();
    t = s;
    if(id == null) {
      System.err.println("第"+count+"次尝试"+System.currentTimeMillis());
      throw new Exception("retry");
    }
  }
}

Retry注解分析

value:当抛出是指定异常的时候 才会去走重试机制; maxAttempts:最大尝试次数 不配置默认是3次; backoff 注解分析delay:时间间隔倍数,比如你配置delay 是1000,multiplier是2,第一次尝试是间隔1秒,第二次就是2秒,第三次就是4秒依次类推。