繁体   English   中英

Spring Retry 不适用于 try-catch 块

[英]Spring Retry doesn't work with a try-catch block

我有一个方法,我想在发生 SQLRecoverableException 时重试。 我用@Retryable(value={SQLRecoverableException.class})注释了该方法并在我的应用程序中启用了重试。 但是,此特定方法包含一个用于处理 RuntimeException 的 try-catch 块。 重试现在不起作用,因为在 try-catch 块中捕获了任何异常。 我希望该方法在错误处理之前重试 3 次。 开箱即用的 Spring Retry 是否可行,还是我必须寻求更自定义的解决方案?

重试不仅可以通过注释处理,所以也许这可以帮助:

try {
    withRetry().execute(context -> {
        myMethodThatCatchException();
        return null;
    });
} catch (RuntimeException re) {
    // ..
}

private RetryTemplate withRetry() {
    RetryTemplate retryTemplate = new RetryTemplate();
    BackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    retryTemplate.setBackOffPolicy(backOffPolicy);
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, Collections.singletonMap(SQLRecoverableException.class, true));
    retryTemplate.setRetryPolicy(retryPolicy);
    return retryTemplate;
}

您可以在 try-catch 块中捕获并重新抛出特定异常

@Retryable(value={SQLRecoverableException.class})
void someMethod() {
   try {
      ...
   } catch (SQLRecoverableException retryable) { 
       // don't handle here, let it be handled by @Retryable-mechanism
       throw retryable;
   } catch (RuntimeException other) {
       // handle other non-retryable exceptions
   }
}
`
@Retryable(value={SQLRecoverableException.class},maxAttempts=3)
public boolean methodA(){
try{.....}
catch(RuntimeException ex){ // apart from given above one
\\handle catch exception
} 
}

@Recover
public boolean recoverMethodA(SQLRecoverableException a){
 logger.info(a.getMessage());
return false;
}

暂无
暂无

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

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