該RestTemplate
有setErrorHandler
選項和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
各地所需的狀態碼。
不是直接的,但如果您可以提供更多關於如何調用服務器的上下文(例如,如果您使用的是Spring集成出站網關,或者您是否直接從代碼中使用'RestTemplate'),我們可能能夠提出解決方案。 – 2014-12-01 21:26:16
我擴展了RestTemplate,並用RetryTemplate覆蓋了它們的幾個方法。我正在按照上面的github鏈接給出的例子,類似於... SimpleRetryPolicy policy = new SimpleRetryPolicy(); policy.setMaxAttempts(5); policy.setRetryableExceptions(new Class [] {HttpServerErrorException.class}); Spring restTemplate爲http狀態錯誤代碼500 - 511報告'HttpServerErrorException.class',但是我想在503和504上重試。 – 2014-12-02 03:50:05
現在,我從doWithRetry(RetryContext上下文)中的RetryContext中拖出throwable並讀取錯誤消息 - context.getLastThrowable()。getMessage(),然後查找503或504.我認爲必須有更好的方法來做到這一點。 – 2014-12-02 03:50:48