2014-12-01 30 views
7

是否可以根據錯誤狀態碼在春季重試中設置RetryPolicy(https://github.com/spring-projects/spring-retry)?例如我想在HttpServerErrorException上重試HttpStatus.INTERNAL_SERVER_ERROR狀態碼,這是503.因此,它應該忽略所有其他錯誤代碼 - [500 - 502]和[504 - 511]。是否可以在基於HttpStatus狀態碼的spring-retry中設置RetryPolicy?

+0

不是直接的,但如果您可以提供更多關於如何調用服務器的上下文(例如,如果您使用的是Spring集成出站網關,或者您是否直接從代碼中使用'RestTemplate'),我們可能能夠提出解決方案。 – 2014-12-01 21:26:16

+0

我擴展了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

+0

現在,我從doWithRetry(RetryContext上下文)中的RetryContext中拖出throwable並讀取錯誤消息 - context.getLastThrowable()。getMessage(),然後查找503或504.我認爲必須有更好的方法來做到這一點。 – 2014-12-02 03:50:48

回答

5

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各地所需的狀態碼。

相關問題