是否可以根据错误状态代码在 spring 重试( https://github.com/spring-projects/spring-retry )中设置 RetryPolicy ?例如,我想HttpServerErrorException
使用HttpStatus.INTERNAL_SERVER_ERROR
状态码重试,即 503。因此它应该忽略所有其他错误代码 - [500 - 502] 和 [504 - 511]。
问问题
11514 次
3 回答
9
RestTemplate
hassetErrorHandler
选项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
所需的状态代码。
于 2014-12-02T15:05:01.810 回答
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();
}
});
}}
Ans 简单地调用它如下:
RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new InternalServerExceptionClassifierRetryPolicy())
于 2018-05-16T18:21:31.650 回答
0
您还可以在 SinmpleRetryPolicy 的 retryableExceptions 列表中添加具体的错误代码。
Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
retryableExceptions.put(HttpClientErrorException.Unauthorized.class, true);
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(5, retryableExceptions));
于 2021-12-21T09:50:04.523 回答