[英]Spring Retry doesn't work with a try-catch block
I have a method that I want to retry when SQLRecoverableException occurs.我有一个方法,我想在发生 SQLRecoverableException 时重试。 I annotated the method with @Retryable(value={SQLRecoverableException.class})
and enabled Retry in my application.我用@Retryable(value={SQLRecoverableException.class})
注释了该方法并在我的应用程序中启用了重试。 However, this specific method includes a try-catch block to handle RuntimeException.但是,此特定方法包含一个用于处理 RuntimeException 的 try-catch 块。 The Retry is now not working because any exception gets caught in the try-catch block.重试现在不起作用,因为在 try-catch 块中捕获了任何异常。 I want the method to be retried for 3 times before the error handling.我希望该方法在错误处理之前重试 3 次。 Is this possible with Spring Retry out of the box, or would I have to go for a more custom solution?开箱即用的 Spring Retry 是否可行,还是我必须寻求更自定义的解决方案?
With Retry can be handled not only via annotation, so maybe this can help:重试不仅可以通过注释处理,所以也许这可以帮助:
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;
}
You can catch and rethrow specific exceptions inside try-catch block您可以在 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.