开发场景
当我们与其他第三方对接口的时候,正常是可以一次成功或是失败,但是偶尔也会遇到第三方网络异常或者响应异常。再或者你调用别人的接口回调的时候。可能需要多次尝试获取响应。
SpringBoot 实现重试机制
- 引入响应jar Maven 对应的pom.xml
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
- 启动类加注解@EnableRetry
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@EnableRetry
public class App {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
System.out.println("hello start");
SpringApplication.run(App.class, args);
System.err.println("hello end");
}
}
- 需要重试的Servcie 方法上加注解配置
@Service
public class RetryServiceImpl implements RetryService {
public int count = 0;
public long t = 0;
@Override
@Retryable(value = RetryException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000 * 2, multiplier = 1.5))
public void TestRetryMethod(String name) {
// TODO Auto-generated method stub
count++;
Long s = System.currentTimeMillis();
t = s;
if(name == null) {
System.err.println("第"+count+"次尝试"+System.currentTimeMillis());
throw new RetryException("retry");
}
}
}
Retryable 注解分析value
/**
* Exception types that are retryable. Synonym for includes(). Defaults to empty (and
* if excludes is also empty all exceptions are retried).
* @return exception types to retry
*/
Class<? extends Throwable>[] value() default {};
通过英语注释可以知道当抛出是这个异常的时候 才会去走重试机制。
Retryable 注解分析maxAttempts
/**
* @return the maximum number of attempts (including the first failure), defaults to 3
*/
int maxAttempts() default 3;
最大尝试次数 不配置默认是3次。
backoff 注解分析delay
/**
* A canonical backoff period. Used as an initial value in the exponential case, and
* as a minimum value in the uniform case.
* @return the initial or canonical backoff period in milliseconds (default 1000)
*/
long delay() default 0;
多少毫秒之后重新尝试。
backoff 注解分析multiplier
这是时间间隔倍数,比如你配置delay 是1000,multiplier是2 也就是一秒 第一次尝试是间隔1秒第二次就是2秒第三次就是4秒依次类推。
总结:底层原理就是aop 思想。