【问题标题】:How to configure RetryTemplate only for Http status code 500?如何仅为 Http 状态码 500 配置 RetryTemplate?
【发布时间】:2018-05-13 11:00:20
【问题描述】:

我正在使用 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;
}

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

【问题讨论】:

标签: java spring spring-boot java-8 spring-retry


【解决方案1】:

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

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2017-11-01
    • 2016-05-29
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多