如何只为 Http 状态码 500 配置 RetryTemplate? [英] How to configure RetryTemplate only for Http status code 500?

查看:57
本文介绍了如何只为 Http 状态码 500 配置 RetryTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 spring-retry(使用 java 8 lambda)来重试失败的 REST 调用.我只想重试那些返回 500 错误的调用.但是我无法为此配置 retrytemplate bean.目前 bean 很简单,如下所示:

I'm using spring-retry (with java 8 lambda) to retry the failed REST calls. I want to retry only for those call which returned 500 error. But I'm not able to configure retrytemplate bean for that. Currently the bean is simple as follows:

@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;
}

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

Can anybody help me with this. Thanks in advance.

推荐答案

所以我通过以下方式创建自定义 RetryPolicy 解决了我的问题:

So I solved my problem by creating custom RetryPolicy in following way:

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();
            }
        });
    }
}

希望这对您有所帮助.

这篇关于如何只为 Http 状态码 500 配置 RetryTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆