我有一个自定义的重试策略,该策略旨在在应用程序收到非404状态的http状态代码时执行重试。我还创建了一个重试模板。我对如何使用重试模板执行自定义重试策略感到困惑。在这方面的任何帮助以及如何测试我的结果都将非常好。我已经包含了重试模板和自定义重试策略的代码。
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(maxBackOffPeriod);
retryTemplate.setBackOffPolicy(backOffPolicy);
NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
public class HttpFailedConnectionRetryPolicy extends ExceptionClassifierRetryPolicy {
@Value("${maxAttempts:-1}")
private String maxAttempts;
public void HttpFailedConnectionRetryPolicy() {
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable classifiable) {
Throwable exceptionCause = classifiable.getCause();
if (exceptionCause instanceof HttpStatusCodeException) {
int statusCode = ((HttpStatusCodeException) classifiable.getCause()).getStatusCode().value();
return handleHttpErrorCode(statusCode);
}
return simpleRetryPolicy();
}
});
}
public void setMaxAttempts(String maxAttempts) {
this.maxAttempts = maxAttempts;
}
private RetryPolicy handleHttpErrorCode(int statusCode) {
RetryPolicy retryPolicy = null;
switch (statusCode) {
case 404:
retryPolicy = doNotRetry();
break;
default:
retryPolicy = simpleRetryPolicy();
break;
}
return retryPolicy;
}
private RetryPolicy doNotRetry() {
return new NeverRetryPolicy();
}
private RetryPolicy simpleRetryPolicy() {
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(Integer.valueOf(maxAttempts));
return simpleRetryPolicy;
}
}
答案 0 :(得分:0)
只需将重试策略的实例而不是SimpleRetryPolicy
注入模板。
要进行测试,您可以在测试用例中向模板添加RetryListener
。