在春季重试中仅处理自定义异常



我想在 Spring 重试中只重试自定义异常。但重试模板会重试所有异常。我的代码:

try {
getRetryTemplate().execute((RetryCallback<Void, IOException>) context -> {
throw new RuntimeException("ddd"); // don't need to retry
});
} catch (IOException e) {
log.error("");
} catch (Throwable throwable) {
log.error("Error .", throwable); // I want catch exception after first attempt
}
private RetryTemplate getRetryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(INITIAL_INTERVAL_FOR_RETRYING);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(MAX_ATTEMPTS);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}

我希望重试器仅在IOException之后重试,但它在所有异常后重试。

我不明白 RetryCallback 中的异常类型出于什么目的,但我发现我可以使用 ExceptionClassifierRetryPolicy 在 RetryTemplate 中指定所需的行为:

private RetryTemplate getRetryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
exponentialBackOffPolicy.setInitialInterval(INITIAL_INTERVAL_FOR_RETRYING);
retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(MAX_ATTEMPTS);
ExceptionClassifierRetryPolicy exceptionClassifierRetryPolicy = new ExceptionClassifierRetryPolicy();
Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
policyMap.put(IOException.class, retryPolicy);
exceptionClassifierRetryPolicy.setPolicyMap(policyMap);
retryTemplate.setRetryPolicy(exceptionClassifierRetryPolicy);
return retryTemplate;
}

使用此配置时,将仅重试 IOException。

最新更新