我是新手spring-retry。基本上,為了重試對 REST API 的呼叫,我已集成spring-retry到我的 spring-boot 應用程式中。為此,我進行了以下更改:
添加
spring-retry到 pom.xml。添加了以下配置:
@Configuration @EnableRetry public class RetryConfiguration { }最后
@Retryable在類(這個類不是Spring Bean)方法中添加了注釋,我想針對各種例外重試如下:public class OAuth1RestClient extends OAuthRestClient { @Override @Retryable(maxAttempts = 3, value = { Exception.class}, backoff = @Backoff(delay = 100, multiplier = 3)) public Response executeRequest(OAuthRequest request) throws InterruptedException, ExecutionException, IOException { System.out.println("Inside Oauth1 client"); return myService.execute(request); }
現在,該executeRequest方法不會重試。我無法理解我是否在這里遺漏了什么。
有人可以幫忙嗎?謝謝。
uj5u.com熱心網友回復:
如果您的類不是 Spring 管理的(例如 @Component/@Bean),則注釋處理器@Retryable將不會接收它。
您始終可以手動定義 aretryTemplate并用它包裝呼叫:
RetryTemplate.builder()
.maxAttempts(2)
.exponentialBackoff(100, 10, 1000)
.retryOn(RestClientException.class)
.traversingCauses()
.build();
進而
retryTemplate.execute(context -> myService.execute(request));
如果您想重試多個例外,這可以通過自定義發生 RetryPolicy
Map<Class(? extends Throwable), Boolean> exceptionsMap = new HashMap<>();
exceptionsMap.put(InternalServerError.class, true);
exceptionsMap.put(RestClientException.class, true);
SimpleRetryPolicy policy = new SimpleRetryPolicy(5, exceptionsMap, true);
RetryTemplate.builder()
.customPolicy(policy)
.exponentialBackoff(100, 10, 1000)
.build();
僅供參考:RetryTemplate正在阻塞,您可能想探索一種非阻塞異步重試方法,例如async-retry。- 并且retryOn()支持例外串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/364430.html
