gpt4 book ai didi

java - 在 spring 重试中仅处理自定义异常

转载 作者:行者123 更新时间:2023-12-01 19:19:42 24 4
gpt4 key购买 nike

我只想在 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。

关于java - 在 spring 重试中仅处理自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59373799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com