我是Spring Boot的新手,无法设置RetryTemplate来重试除404以外的所有失败的异常代码。以下是我的代码:
@Bean
public RetryTemplate createRetryTemplate() {
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts);
UniformRandomBackOffPolicy backOffPolicy = new UniformRandomBackOffPolicy();
backOffPolicy.setMinBackOffPeriod((long) minBackOffPeriod);
backOffPolicy.setMaxBackOffPeriod(maxBackOffPeriod);
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);
return retryTemplate;
}
我了解我需要制定政策,但是不确定如何制定。任何帮助将不胜感激。
最佳答案
我将尝试使用ExceptionClassifierRetryPolicy
来检测引发的异常的类型,并基于该异常返回不同的重试策略:
class HttpStatusRetryPolicy extends ExceptionClassifierRetryPolicy {
public HttpStatusRetryPolicy() {
final NeverRetryPolicy doNotRetry = new NeverRetryPolicy();
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
// configure your RetryPolicy here:
// retryPolicy.setMaxAttempts(maxAttempts);
// ...
this.setExceptionClassifier(throwable -> {
if (throwable instanceof HttpClientErrorException.NotFound) { // 404
return doNotRetry;
}
return simpleRetryPolicy;
});
}
}