使用重试模板执行自定义重试策略



>我有一个自定义重试策略,旨在每当应用程序收到非 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;
}

}

只需将重试策略的实例注入模板而不是SimpleRetryPolicy即可。

若要进行测试,可以在测试用例中向模板添加RetryListener

最新更新