一Spring-retry簡(jiǎn)介
??有些場(chǎng)景需要我們對(duì)一些異常情況下面的任務(wù)進(jìn)行重試,比如:調(diào)用遠(yuǎn)程的RPC服務(wù),可能由于網(wǎng)絡(luò)抖動(dòng)出現(xiàn)第一次調(diào)用失敗,嘗試幾次就可以恢復(fù)正常。
??spring-retry是spring提供的一個(gè)基于spring的重試框架,非常好用。
官網(wǎng)地址: https://github.com/spring-projects/spring-retry
二、Maven依賴(lài)
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
三、重試使用
- 啟動(dòng)類(lèi)添加注解@EnableRetry
@SpringBootApplication
@EnableTransactionManagement // 啟注解事務(wù)管理
@EnableScheduling
@EnableRetry // 啟用了重試功能
public class TestWebApplication {
public static void main(String[] args) {
SpringApplication.run(TestWebApplication.class, args);
}
}
- 業(yè)務(wù)方法重試
@Service
@Slf4j
public class RetryServiceImpl implements RetryService {
private AtomicInteger count = new AtomicInteger(1);
@Override
@Retryable(value = { RemoteAccessException.class }, maxAttemptsExpression = "${retry.maxAttempts:10}",
backoff = @Backoff(delayExpression = "${retry.backoff:1000}"))
public void retry() {
log.info("start to retry : " + count.getAndIncrement());
throw new RemoteAccessException("here " + count.get());
}
@Recover
public void recover(RemoteAccessException t) {
log.info("SampleRetryService.recover:{}", t.getClass().getName());
}
}
【注意】@Recover 的用法。它要求它注釋的方法的返回值必須和@Retryable的注釋的方法返回值保持一致,否則@Recover 注釋的方法不會(huì)被調(diào)用。它還有關(guān)于自己參數(shù)的使用要求。
- 自定義retry
public static void main(String[] args) throws InterruptedException {
RetryTemplate template = new RetryTemplate();
TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
policy.setTimeout(2000L);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
// 重試策略
template.setRetryPolicy(retryPolicy);
String result = template.execute(context -> {
System.out.println("TestAll.main()1");
TimeUnit.SECONDS.sleep(1L);
throw new IllegalArgumentException();
}, context -> {
System.out.println("TestAll.main()2");
return "world";
});
System.out.println("result:" + result);
}
【注意】
interface RetryPolicy 它有很多的實(shí)現(xiàn)類(lèi)可以使用。
四、常用注解
- @Retryable注解
被注解的方法發(fā)生異常時(shí)會(huì)重試
value:指定發(fā)生的異常進(jìn)行重試
include:和value一樣,默認(rèn)空,當(dāng)exclude也為空時(shí),所有異常都重試
exclude:指定異常不重試,默認(rèn)空,當(dāng)include也為空時(shí),所有異常都重試
maxAttemps:重試次數(shù),默認(rèn)3
backoff:重試補(bǔ)償機(jī)制,默認(rèn)沒(méi)有 - @Backoff注解
delay:指定延遲后重試
multiplier:指定延遲的倍數(shù),比如delay=5000l,multiplier=2時(shí),第一次重試為5秒后,第二次為10秒,第三次為20秒 - @Recover
當(dāng)重試到達(dá)指定次數(shù)時(shí),被注解的方法將被回調(diào),可以在該方法中進(jìn)行日志處理。需要注意的是發(fā)生的異常和入?yún)㈩?lèi)型一致時(shí)才會(huì)回調(diào)。