首页 文章

Spring Batch:在容错步骤中调整事务属性

提问于
浏览
3

我在Spring Batch作业中有一个非常基本的步骤(使用Java配置):

@Bean
public Step step1() {
    return stepBuilders.get("stepName")
        .<Object1, Void>chunk(50)
        .reader(reader(inputResource(null))
        .processor(processor())
        .listener(stepLogger())
        .transactionAttribute(transactionTimeoutAttribute(null))
        .build();
}

   .......

@Bean
@StepScope
public StepExecutionListener stepLogger() {
    return new StepLogger();
}

@Bean
@StepScope
public TransactionAttribute transactionTimeoutAttribute(
        @Value("#{jobParameters[transactionTimeout]}") Integer timeout) {
    timeout = timeout != null ? timeout : DEFAULT_TRANSACTION_TIMEOUT;
    RuleBasedTransactionAttribute transactionAttribute = new RuleBasedTransactionAttribute();
    transactionAttribute.setTimeout(timeout);
    return transactionTimeout;
}

如您所见,要求事务超时可以作为作业参数给出 . 这完美的作品,如果我设置transactionTimeout工作参数过低,作业执行将块完成之前的交易时失败了 .

但是,如果我试图提高容错能力(能够跳过一定数量的失败元素),一切都会崩溃 . 当我将faultTolerant()添加到步骤配置中以便能够指定跳过策略等时,如下所示:

@Bean
public Step step1() {
    return stepBuilders.get("stepName")
        .<Object1, Void>chunk(50)
        .reader(reader(inputResource(null))
        .processor(processor())
        .faultTolerant()
        .listener(stepLogger())
        .transactionAttribute(transactionTimeoutAttribute(null))
        .build();
}

Spring不能再启动上下文(现在在Jetty上),只是在启动时抛出以下异常:

BeanCreationException: Error creating bean with name 'scopedTarget.transactionTimeoutAttribute': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope

使用Java Config在Spring Batch中指定事务属性和跳过策略的正确方法是什么?

EDIT: 只是为了使问题多一点理解,我的要求是使容错步骤,其中事务超时是可配置的工作参数 . 对于非容错一步,这不是一个问题,只要一个步骤作用域TransactionAttribute beans 与有线的工作参数,但FaultTolerantStepBuilder处理事务属性不同(它基本上融合了其内部的一个给定的事务属性),所以步骤范围不可用 . 如何使用作业参数配置容错步骤(Java config)的事务属性?

1 回答

  • 0

    如果您使用的是Spring Batch 3或更新版本,则可以将事务属性标记为@JobScope . 这将阻止容错步骤过早访问事务属性 .

相关问题