開發場景
當我們與其他第三方對接口的時候,正常是可以一次成功或是失敗,但是偶爾也會遇到第三方網絡異常或者響應異常。再或者你調用別人的接口回調的時候。可能需要多次嘗試獲取響應。
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 思想。