[英]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.