【问题标题】:How to Configure a RetryTemplate in Spring Batch with Java Configuration如何使用 Java 配置在 Spring Batch 中配置 RetryTemplate
【发布时间】:2021-06-23 17:38:09
【问题描述】:

我正在尝试在 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 配置进行设置的示例/模板吗?

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

【问题讨论】:

    标签: spring spring-batch spring-retry retrypolicy


    【解决方案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 方法。

    【讨论】:

    • 谢谢@Mahmoud Ben Hassine,这就是我要找的。如何实现 ExponentialBackOffPolicy。作为 Spring,我认为实现/布线不会很困难。
    猜你喜欢
    • 2012-08-27
    • 1970-01-01
    • 2018-08-21
    • 2018-01-17
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2014-01-04
    • 2015-04-30
    相关资源
    最近更新 更多