Spring Retry提供了操作重試的功能,在網(wǎng)絡(luò)不穩(wěn)定的情況下,重試功能是比較重要的必備項(xiàng)。Spring Retry可以讓我們自定義重試策略,回退策略,重試狀態(tài)處理。
使用
1 添加依賴,默認(rèn)情況下在Spring Boot中有依賴項(xiàng)。
<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();
// 每次回退固定的時(shí)間
// 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有一個(gè)缺點(diǎn),其回退策略,默認(rèn)使用的是Thread.sleep方法,會(huì)導(dǎo)致當(dāng)前的線程被阻塞,因此使用的時(shí)候要注意。
最后
簡(jiǎn)單說(shuō)明了下Spring Retry的使用方式,使用簡(jiǎn)單,功能強(qiáng)大。