简体   繁体   English

Spring重试异常处理执行行为

[英]Spring retry exception handling execution behavior

I am trying to get to the best way to wrap spring-retry @Retryable annotation around external service call.我正在尝试以最佳方式将spring-retry @Retryable注释包装在外部服务调用周围。 Here is my code:这是我的代码:

@Retryable(exclude = HttpClientErrorException.BadRequest.class, value = RestClientException.class)
private ResponseEntity<Item> retrieveItemById(String id) 
{
    HttpHeaders headers = new HttpHeaders();
    try {
        return restTemplate.exchange(httpConnectionProperties.getBaseUrl() + "/items",
                HttpMethod.GET, new HttpEntity<>(item, headers), Item.class, id);
    } 
    catch (RestClientException e) {
        log.error("Exception occurred while retrieving an item" , e);
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

I have a few questions on what happens when a RestClientException occurs :关于发生RestClientException时会发生什么,我有几个问题:

  1. Is the catch block executed before retry kicks in or does the retry kicks in before the catch block execution?是在retry开始之前执行catch 块还是在catch 块执行之前开始重试? Do I need a recovery block?我需要恢复块吗?
  2. Probably more of an exception handling question - Is there a way to differentiate between an actual retry worthy scenario (service momentarily down, network issues, I/O error etc.) vs exception occurring due to lack of presence of an item in the above case?可能更多的是异常处理问题 - 有没有办法区分实际的重试场景(服务暂时关闭、网络问题、I/O 错误等)与在上述情况下由于缺少项目而发生的异常?

Since you are catching and "handling" the exception, retry is disabled;由于您正在捕获并“处理”异常,因此重试被禁用; retry will only work if the method throws an exception.仅当方法引发异常时,重试才会起作用。

To change the result (instead of throwing the exception to the caller when retries are exhausted, you need a @Recover method.要更改结果(而不是在重试用尽时向调用者抛出异常,您需要一个@Recover方法。

Not retryable exceptions will go straight there;不可重试的异常会直接出现; you can have multiple @Recover methods for different exception types, or one generic one and you can check the exception type yourself.您可以为不同的异常类型设置多个@Recover方法,或者使用一个通用的方法,您可以自己检查异常类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM