如何仅针对 Http 状态码 500 配置 RetryTemplate?

How to configure RetryTemplate only for Http status code 500?

我正在使用 spring-retry(使用 java 8 lambda)重试失败的 REST 调用。我只想重试那些返回 500 错误的调用。但是我无法为此配置重试模板 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;
}

谁能帮我解决这个问题。提前致谢。

所以我通过以下方式创建自定义 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();
            }
        });
    }
}

希望对您有所帮助。