我正在使用Spring Boot应用程序,并且正在使用Rest Templates集成某些失败的HTTP连接的重试。我已经集成了其余模板并为其配置了超时,现在我集中精力执行具有自定义重试策略的重试模板,但是遇到了一些问题。我拥有的自定义重试策略位于单独的类中,但是我试图将其集成到创建重试模板的同一类中。我在下面包含了用于创建重试模板的代码,单独的自定义重试策略类,还尝试将自定义重试策略与重试模板代码集成在一起。自定义重试策略设置为在应用程序获取HTML代码404时触发重试。
公共类HttpFailedConnectionRetryPolicy扩展了ExceptionClassifierRetryPolicy {
public HttpFailedConnectionRetryPolicy(Integer maxAttempts) {
final NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(maxAttempts);
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable throwable) {
if (throwable instanceof HttpClientErrorException.NotFound) {
return doNotRetry;
}
return simpleRetryPolicy;
}
});
}
}
公共RetryTemplate retryTemplate()抛出Throwable { RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod((long) maxBackOffPeriod);
retryTemplate.setBackOffPolicy(backOffPolicy);
NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate.execute(new RetryCallback<RetryTemplate, Throwable>() {
@Override
public RetryTemplate doWithRetry(RetryContext retryContext) throws Throwable {
class HttpFailedConnectionRetryPolicy extends ExceptionClassifierRetryPolicy {
public HttpFailedConnectionRetryPolicy() {
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable throwable) {
if (throwable instanceof HttpClientErrorException.NotFound) {
return doNotRetry;
}
return retryPolicy;
}
});
}
}
}
class HttpFailedConnectionRetryPolicy extends ExceptionClassifierRetryPolicy {
public HttpFailedConnectionRetryPolicy() {
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable throwable) {
if (throwable instanceof HttpClientErrorException.NotFound) {
return doNotRetry;
}
return retryPolicy;
}
});
}
}
});
}