[英]Spring RestTemplate: Exponential Backoff retry policy
我正在閱讀GCM: https : //developers.google.com/cloud-messaging/server
其中一個要求是服務器需要能夠:
我使用Spring RestTemplate作為我的后端,它來自Spring Boot。 似乎沒有一種方法可用於在文檔中設置我的重試策略: http : //docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/ RestTemplate.html
另外,當我用Google搜索時,我找到了RetryTemplate,但它是Spring Batch的一部分,並沒有擴展RestTemplate,這讓我覺得它不應該用於Rest操作,而是Spring Batch操作,比如處理大量的事務: http : //docs.spring.io/spring-batch/2.1.x/apidocs/org/springframework/batch/retry/support/RetryTemplate.html
有沒有辦法可以使用Spring RestTemplate進行指數退避?
美好的一天!
我想,通過實現自定義Sleeper類可以實現期望的行為。
接下來,您需要將此睡眠器設置為BackOffPolicy ,如下所示:
public class RetryTest {
public static final Logger LOG = LoggerFactory.getLogger(RetryTemplate.class);
@org.junit.Test
public void testRT() {
RetryTemplate retryTemplate = new RetryTemplate();
final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
Sleeper sleeper = new Sleeper() {
private long timeToSleep = 0;
@Override
public void sleep(long timeout) throws InterruptedException {
if (timeToSleep ==0) {
timeToSleep = timeout;
} else {
timeToSleep = (long) (timeToSleep * Math.E);
}
LOG.warn("sleeping for: {}", timeToSleep);
Thread.sleep(timeToSleep);
}
};
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy().withSleeper(sleeper);
retryTemplate.setBackOffPolicy(backOffPolicy);
retryTemplate.execute(new RetryCallback<Void, ResourceAccessException>() {
@Override
public Void doWithRetry(RetryContext retryContext) throws ResourceAccessException {
LOG.debug(">RetryCount: {}", retryContext.getRetryCount());
new RestTemplate().getForObject("https://unreachable.host", String.class);
return null;
}
});
}
}
彈簧重試也有ExponentialBackOffPolicy 。
希望這會有所幫助。
您可以像下面的代碼一樣使用。
@Retryable(exceptionExpression="#{@exceptionChecker.shouldRetry(#root)}",
maxAttemptsExpression = "#{@integerFiveBean}",
backoff = @Backoff(delayExpression = "#{1}",
maxDelayExpression = "#{5}", multiplierExpression = "#{1.1}"))
public void service3() {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.