我使用spring-retry(使用java 8 lambda)重试失败的REST调用。我想只为那些返回500错误的调用重试。但是我无法为此配置retrytemplate bean。目前bean很简单如下:
@Bean("restRetryTemplate")
public RetryTemplate retryTemplate() {
Map<Class<? extends Throwable>, Boolean> retryableExceptions= Collections.singletonMap(HttpServerErrorException.class,
Boolean.TRUE);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, retryableExceptions);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
任何人都可以帮助我。提前谢谢。
答案 0 :(得分:3)
所以我通过以下方式创建自定义RetryPolicy解决了我的问题:
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy());
,实施如下:
public class InternalServerExceptionClassifierRetryPolicy extends ExceptionClassifierRetryPolicy {
public InternalServerExceptionClassifierRetryPolicy() {
final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
simpleRetryPolicy.setMaxAttempts(3);
this.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {
@Override
public RetryPolicy classify(Throwable classifiable) {
if (classifiable instanceof HttpServerErrorException) {
// For specifically 500 and 504
if (((HttpServerErrorException) classifiable).getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR
|| ((HttpServerErrorException) classifiable)
.getStatusCode() == HttpStatus.GATEWAY_TIMEOUT) {
return simpleRetryPolicy;
}
return new NeverRetryPolicy();
}
return new NeverRetryPolicy();
}
});
}
}
希望这会对你有帮助。