【问题标题】:Not able to understand spring retry无法理解春季重试
【发布时间】:2021-03-17 10:39:46
【问题描述】:

我正在努力理解@Retryable。我需要的是在收到 5xx 异常时重试 3 次,如果重试也失败,则在恢复方法中抛出自定义异常。如果抛出了其他异常,则捕获它并抛出自定义异常。

@Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))
public String callToService(String key) {
        String response;
        try {
            response =  //assume a service call here
            
        }catch (Exception ex) {
            throw new customException("some message");
        }
        return response;
}
    
@Recover
public void retryFailed(HttpServerErrorException httpServerErrorException) {
    throw new customException("some message");
}

【问题讨论】:

    标签: spring-boot spring-retry


    【解决方案1】:

    在您添加的情况下: @Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))

    @Retryable 用于:

    1. value = HttpServerErrorException.class,因此只有在您的方法代码中出现/抛出HttpServerErrorException 时才会重试您的方法,并且注意:如果抛出任何其他异常,则不会重试完成,并且恢复方法也不会被调用,因为恢复方法只会在@Retryable中的值中提到的异常情况下被调用。
    2. maxAttempts = 3,所以它会重试执行你的方法最多 3 次
    3. backoff = @Backoff(delay = 3000),所以它会在重试之间保持 3000 毫秒的延迟。
    4. 重试3次后,如果你的方法还是不行,你的@Recover方法会被HttpServerErrorException调用

    我希望它有意义并帮助你理解@Retryable的概念

    现在要实现你想要的,你需要如下实现它:

    @Retryable(value = HttpServerErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 3000))
    public String callToService(String key) {
            String response;
            try {
                response =  //assume a service call here
            } catch (HttpServerErrorException httpServerErrorException) {
                throw httpServerErrorException;
            } catch (Exception ex) {
                throw new CustomException("some message");
            }
            return response;
    }
        
    @Recover
    public void retryFailed(HttpServerErrorException httpServerErrorException) {
        //do whatever you want here, when HttpServerErrorException occured more than 3 times
    }
    

    【讨论】:

    • 感谢您的帮助。虽然当我在上面尝试时,正在重试,但没有调用恢复方法。后来发现Recover注解的方法需要和Retryable注解的方法有相同的签名
    猜你喜欢
    • 2018-02-08
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多