首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在达到弹性最大尝试次数后处理异常4j-使用Spring Boot重试

在达到弹性最大尝试次数后处理异常4j-使用Spring Boot重试
EN

Stack Overflow用户
提问于 2020-10-13 20:46:43
回答 1查看 1.4K关注 0票数 1

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

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

代码语言:javascript
复制
@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
}

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

代码语言:javascript
复制
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的时候。我希望在每次重试时捕获自定义的运行时捕捉,并在最后一次重试(当达到maxAttempt时)抛出,因此我将调用包装在MyRestException -catch中。

代码语言:javascript
复制
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-重试机制。

如何实现maxAttempts命中时的行为?有没有办法为这种情况定义特定的回退方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-14 21:45:36

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

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

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64335573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档