java - 在春季重试中仅处理自定义异常
问题描述
我想在 Spring 重试中只重试自定义异常。但是 retryTemplate 会重试所有异常。我的代码:
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。
推荐阅读
- typescript - CollectionReference.doc() 要求它的第一个参数是非空字符串类型
- javascript - 这一行Javascript代码的性能提升
- python-3.x - 不将字符串值转换为整数值
- php - 匹配格式为 (+-)(数字或字母)(冒号)的任何字符串
- css - Laravel 链接到不同页面上的另一个部分
- python - ModuleNotFoundError:没有名为efficientnet.tfkeras 的模块
- python - 如何修复 For 循环以从 DataFrame 返回某个字符?
- git - 如何将来自源的提交提交到我的本地分支?
- python-3.x - 如何使用 Pandas 比较和计算高/低值
- mysql - 如何与随机和限制联合选择