我正在阅读 GCM:https://developers.google.com/cloud-messaging/server
其中一项要求是服务器需要能够:
- 处理请求并使用指数退避重新发送它们。
我的后端使用来自 Spring Boot 的 Spring RestTemplate。似乎没有可用于在文档中设置重试策略的方法:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
另外,当我用谷歌搜索时,我找到了 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通过 Spring 重试。
希望这会有所帮助。
关于java - Spring RestTemplate : Exponential Backoff retry policy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906419/