是否可以根据HttpStatus状态代码在spring-retry中设置RetryPolicy?

时间:2014-12-01 19:56:53

标签: spring spring-retry

是否可以根据错误状态代码在spring retry(https://github.com/spring-projects/spring-retry)中设置RetryPolicy?例如我想在HttpServerErrorException上使用HttpStatus.INTERNAL_SERVER_ERROR状态代码重试,即503.因此,它应该忽略所有其他错误代码 - [500 - 502]和[504 - 511]。

2 个答案:

答案 0 :(得分:7)

RestTemplatesetErrorHandler选项,DefaultResponseErrorHandler是默认选项。

它的代码如下:

public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = getHttpStatusCode(response);
    switch (statusCode.series()) {
        case CLIENT_ERROR:
            throw new HttpClientErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
        case SERVER_ERROR:
            throw new HttpServerErrorException(statusCode, response.getStatusText(),
                    response.getHeaders(), getResponseBody(response), getCharset(response));
        default:
            throw new RestClientException("Unknown status code [" + statusCode + "]");
    }
}

因此,您可以为该方法提供自己的实现,以简化RetryPolicy所需的状态代码。

答案 1 :(得分:2)

对于遇到同样问题的其他人,我发布了这个答案。 实现自定义重试策略如下:

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

Ans简单地称之为:

RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy())