有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何仅为Http状态代码500配置RetryTemplate?

我使用SpringRetry(使用Java8Lambda)来重试失败的REST调用。我只想为那些返回500错误的呼叫重试。但我无法为此配置RetryTemplatebean。目前,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;
}

有人能帮我吗。提前谢谢


共 (1) 个答案

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

    希望这能对你有所帮助