Spring Retry提供了操作重試的功能,在網絡不穩(wěn)定的情況下,重試功能是比較重要的必備項。Spring Retry可以讓我們自定義重試策略,回退策略,重試狀態(tài)處理。
使用
1 添加依賴,默認情況下在Spring Boot中有依賴項。
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<!-- <version>1.1.5.RELEASE</version> -->
</dependency>
<!-- Spring Retry使用了AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
2 配置RetryTemplate,重試策略,回退策略?;蛘?strong>監(jiān)聽器
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
// 每次回退固定的時間
// FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
// fixedBackOffPolicy.setBackOffPeriod(2000l);
// 指數回退,第一次回退0.2s,第二次回退0.4s
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(200L);
exponentialBackOffPolicy.setMultiplier(2);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
// 重試策略,有多種重試策略
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(3);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setThrowLastExceptionOnExhausted(false);
return retryTemplate;
}
3 使用重試功能
retryTemplate.execute((RetryCallback<Void, RuntimeException>) context -> {
// 這里寫我們的業(yè)務代碼
// ....
// 模擬拋出異常
throw new RuntimeException("異常");
});
4 可以開啟日志查看效果
logging.level.org.springframework.retry=debug

1569552787010
注解
- @Retryable
- @Recover
- @Backoff
注意
Spring Retry有一個缺點,其回退策略,默認使用的是Thread.sleep方法,會導致當前的線程被阻塞,因此使用的時候要注意。
最后
簡單說明了下Spring Retry的使用方式,使用簡單,功能強大。