如何使用 Java 配置在 Spring Batch 中配置 RetryTemplate

问题描述

我正在尝试在 Spring Batch 中设置 RetryTemplate,但找不到有关如何将 RetryTemplate 添加到 StepBuilderFactory 的示例。我发现这个例子在 SpringBoot 应用程序中设置它,https://dzone.com/articles/how-to-use-spring-retry-template 但在 Spring Batch 上没有运气。

我尝试使用 RetryTemplate 的原因是设置指数 BackOffPolicy (Spring Batch how to configure retry period for failed jobs)。

我想连接 RetryTemplate 就像设置 RetryTemplate Bean 一样简单,类似的东西(来自 @Mahmoud Ben Hassine 答案 Spring Batch how to configure retry period for failed jobs修改代码):

@Bean
public RetryTemplate testExponentialBackoff() throws Exception {
        // configure backoff policy
        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
        exponentialBackOffPolicy.setinitialInterval(1000);
        exponentialBackOffPolicy.setMultiplier(2.0);
        exponentialBackOffPolicy.setMaxInterval(10000);

        // configure retry policy
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        simpleRetryPolicy.setMaxAttempts(5);

        // configure retry template
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        return retryTemplate;
    }

我没有找到将它连接到 StepBuilderFactory 的方法。 我想它会类似于“标准”重试:

  .faultTolerant()
  .retryLimit(3)
  .retry(ConnectTimeoutException.class)

有人有关于如何使用 Java 配置进行设置的示例/模板吗?

感谢任何帮助/示例。谢谢,马库斯。

解决方法

如果您的目标是设置自定义退避策略,则无需为此提供完整的 RetryTemplate,您可以使用 FaultTolerantStepBuilder#backOffPolicy 方法来实现,例如:

// configure backoff policy
ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
// customize exponentialBackOffPolicy as needed

Step step = stepBuilderFactory.get("step")
        .chunk(5)
        // configure reader/writer etc
        .faultTolerant()
        .backOffPolicy(exponentialBackOffPolicy)
        // set other properties
        .build();

现在,如果您真的想提供自定义 RetryOperations 对象,则需要扩展 FaultTolerantStepBuilder 并覆盖 createRetryOperations 方法。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...