【问题标题】:Handle exception after reaching max attempts in resilience4j-retry using Spring Boot使用 Spring Boot 达到最大弹性 4j 重试尝试后处理异常
【发布时间】:2020-10-14 21:45:36
【问题描述】:

我有一个场景,我想记录每次重试尝试,当最后一次尝试失败(即达到maxAttempts)时,抛出异常,假设创建了一个数据库条目。

我尝试使用带有 Spring Boot 的 Resilience4j-retry 来实现这一点,因此我使用 application.yml 和注释。

@Retry(name = "default", fallbackMethod="fallback")
@CircuitBreaker(name = "default", fallbackMethod="fallback")
public ResponseEntity<List<Person>> person() {
    return restTemplate.exchange(...);               // let's say this always throws 500
}

回退将异常原因记录到应用程序日志中。

public ResponseEntity<?> fallback(Exception e) {
    var status = HttpStatus.INTERNAL_SERVER_ERROR;
    var cause = "Something unknown";
    if (e instanceof ResourceAccessException) {
        var resourceAccessException = (ResourceAccessException) e;
        if (e.getCause() instanceof ConnectTimeoutException) {
            cause = "Connection timeout";
        }
        if (e.getCause() instanceof SocketTimeoutException) {
            cause = "Read timeout";
        }
    } else if (e instanceof HttpServerErrorException) {
        var httpServerErrorException = (HttpServerErrorException) e;
        cause = "Server error";
    } else if (e instanceof HttpClientErrorException) {
        var httpClientErrorException = (HttpClientErrorException) e;
        cause = "Client error";
     } else if (e instanceof CallNotPermittedException) {
        var callNotPermittedException = (CallNotPermittedException) e;
        cause = "Open circuit breaker";
    }
    var message = String.format("%s caused fallback, caught exception %s", 
        cause, e.getMessage());
    log.error(message);                                         // application log entry
    throw new MyRestException (message, e);
}

当我调用此方法person() 时,重试发生为maxAttempt 配置。我希望我的自定义运行时 MyRestException 在每次重试时被捕获并在最后一次重试时抛出(当达到 maxAttempt 时),所以我将调用包装在 try-catch 中。

public List<Person> person() {
    try {
        return myRestService.person().getBody();
    } catch (MyRestException ex) {
        log.error("Here I am ready to log the issue into the database");
        throw new ex;
    }
}

不幸的是,当回退遇到并重新抛出立即被我的try-catch 而不是 Resilience4j-retry 机制捕获的异常时,重试似乎被忽略了。

如何实现maxAttempts 被击中时的行为?有没有办法为这种情况定义特定的后备方法?

【问题讨论】:

    标签: java spring spring-boot resilience4j resilience4j-retry


    【解决方案1】:

    您为什么不在您的 Service 方法中捕获异常并将其映射到 MyRestException,例如myRestService.person()? 它使您的配置更加简单,因为您只需将MyRestException 添加到您的 RetryConfig 和 CircuitBreakerConfig 的配置中。

    如果您不想将样板代码添加到每个服务方法中,Spring RestTemplate 还具有注册自定义 ResponseErrorHandler 的机制。 -> https://www.baeldung.com/spring-rest-template-error-handling

    我不会将CallNotPermittedException 映射到MyRestException。您不想在断路器打开时重试。将 CallNotPermittedException 添加到 RetryConfig 中忽略的异常列表中。

    我认为您根本不需要后备机制。我将一个异常映射到另一个异常不是“回退”。

    【讨论】:

    • 感谢您的回答!我总结了在服务层没有回退的异常处理,但是我想避免每个方法的样板代码 - RestTemplate 错误处理机制很好,除了它不能处理超时错误(ConnectTimeoutExceptionSocketTimeoutException...),只要ClientHttpResponse 必须通过服务器/客户端。你有办法解决这个问题吗?
    • 如果答案有帮助,请接受 ;) 您可以使用我们的 SupplierUtils.andThen 和自定义 resultHandler 函数将 ResourceAccessException 映射到 MyRestException
    • 我想避免将application.yml+annotations 配置与功能装饰器配置混用,只要我发现注解更易于使用。我已经在错误处理中包装了每个RestTemplate 调用。在使用 Resilience4j 注释注释的方法中调用该方法(rest 调用 + 错误处理包装器),并且重试真正按我的意愿工作。如果它在 Resilience4j 方面是一个很好的实践,你会检查这个 sn-p 吗? codepile.net/pile/RB5dqQWM
    • 是的,看起来不错
    猜你喜欢
    • 2020-03-10
    • 2020-07-18
    • 2021-03-07
    • 2019-07-12
    • 2020-11-03
    • 1970-01-01
    • 2018-11-19
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多