春季重试例外处理执行行为

发布于 2025-02-13 09:41:47 字数 911 浏览 2 评论 0原文

我正在尝试采用最佳方法来包装春季重返 @retryable围绕外部服务调用的注释。这是我的代码:

@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);
    }
}

我有几个问题,即RESTCLIENTEXCEPTION发生时会发生什么:

  1. 是在retry启动之前执行的捕获块,还是在捕获之前重试块执行?我需要一个恢复块吗?
  2. 可能更多的例外处理问题 - 是否有一种方法可以区分实际的重试值得的场景(服务暂时降低,网络问题,I/O错误等)与由于上述情况不存在项目而导致的例外情况?

I am trying to get to the best way to wrap spring-retry @Retryable annotation around external service call. 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 :

  1. Is the catch block executed before retry kicks in or does the retry kicks in before the catch block execution? 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆兒滾 2025-02-20 09:41:47

由于您正在捕获和“处理”例外,因此重试被禁用;仅当方法引发异常时,重试才能工作。

要更改结果(而不是在恢复耗尽时将异常扔给呼叫者,您需要一个@Recover方法。

不可重复的例外将直接出现在那里;您可以拥有多个@recover < /代码>用于不同异常类型的方法,或一种通用类型,您可以自己检查异常类型。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文