0

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

我尝试使用 RetryTemplate 的原因是设置指数 BackOffPolicy (Spring Batch 如何为失败的作业配置重试周期)。

我想连接 RetryTemplate 就像设置 RetryTemplate Bean 一样简单,类似的东西(来自@Mahmoud Ben Hassine 的修改代码回答Spring Batch 如何为失败的作业配置重试周期):

@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 配置进行设置的示例/模板吗?

任何帮助/示例表示赞赏。谢谢,马库斯。

4

1 回答 1

1

如果您的目标是设置自定义退避策略,则无需为此提供整体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方法。

于 2021-06-24T07:21:36.197 回答