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

Mar*_*nov 9 spring spring-retry

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

Art*_*lan 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 + "]");
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Vai*_*ibS 7

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

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();
        }
    });
}}
Run Code Online (Sandbox Code Playgroud)

Ans 简单地称之为如下:

RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy())
Run Code Online (Sandbox Code Playgroud)