Spring Retry提供了操作重試的功能马澈,在網(wǎng)絡(luò)不穩(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,重試策略凝果,回退策略祝迂。或者監(jiān)聽器
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
// 每次回退固定的時間
// FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
// fixedBackOffPolicy.setBackOffPeriod(2000l);
// 指數(shù)回退器净,第一次回退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è)務(wù)代碼
// ....
// 模擬拋出異常
throw new RuntimeException("異常");
});
4 可以開啟日志查看效果
logging.level.org.springframework.retry=debug
1569552787010
注解
- @Retryable
- @Recover
- @Backoff
注意
Spring Retry有一個缺點山害,其回退策略纠俭,默認使用的是Thread.sleep方法,會導(dǎo)致當(dāng)前的線程被阻塞浪慌,因此使用的時候要注意柑晒。
最后
簡單說明了下Spring Retry的使用方式,使用簡單眷射,功能強大匙赞。