首页 > 解决方案 > 在春季重试中仅处理自定义异常

问题描述

我想在 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 之后重试,但它会在所有异常之后重试。

标签: javaspring-retry

解决方案


我不明白 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。


推荐阅读