如何使Spring批处理步骤取决于上一步?
问题描述:
我使用Spring Batch从CSV文件中读取一些数据并将其放入数据库中。 我的批处理作业必须是2个的步骤化合物如何使Spring批处理步骤取决于上一步?
- 检查文件(名称,扩展,内容..)从CSV
- 读取行,并将它们保存在DB(ItemReader,ItemProcessor中, ItemWriter ..)
如果Step 1
产生错误Step 2
不能执行(文件不符合,文件不存在...)
仅供参考,我使用Spring Batch的XML没有configura重刑!只有注释: 这里是我的工作,配置类的样子:
@Configuration
@EnableBatchProcessing
public class ProductionOutConfig {
@Autowired
private StepBuilderFactory steps;
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private ProductionOutTasklet productionOutTasklet;
@Autowired
private CheckFilesForProdTasklet checkFilesForProdTasklet;
@Bean
public Job productionOutJob(@Qualifier("productionOut")Step productionOutStep,
@Qualifier("checkFilesForProd") Step checkFilesForProd){
return jobBuilderFactory.get("productionOutJob").start(checkFilesForProd).next(productionOutStep).build();
}
@Bean(name="productionOut")
public Step productionOutStep(){
return steps.get("productionOut").
tasklet(productionOutTasklet)
.build();}
@Bean(name = "checkFilesForProd")
public Step checkFilesForProd(){
return steps.get("checkFilesForProd")
.tasklet(checkFilesForProdTasklet)
.build();
}
}
答
已经是你正在寻找的,如果前面的步骤失败将不会被执行Spring Batch的即下一步的默认行为。要将当前步骤标记为失败步骤,您需要抛出未捕获的运行时异常。
如果未处理异常,spring批处理会将该步骤标记为失败,并且下一步将不会执行。所以你只需要在失败的场景中抛出异常。
对于复杂的工作流,你可能会想用 - JobExecutionDecider,Programmatic Flow Decisions
答
由于文档指定您可以使用方法“”如果从先前的状态,退出状态相匹配的,其开始新状态的转变给定模式。
你的代码可能是类似这样的:
return jobBuilderFactory.get("productionOutJob")
.start(checkFilesForProd)
.on(ExitStatus.FAILED.getExitCode()).end()
.from(checkFilesForProd)
.on("*")
.to(productionOutStep)
.build();
我改变这样的:'返回jobBuilderFactory.get( “productionOutJob”) 。开始(checkFilesForProd) 。对(ExitStatus.FAILED。 。getExitCode())结束() 。从(productionOutStep) .END() .build();' 我认为在逻辑上是正确的,但现在我找不到如何返回'ExitStatus.FAILED'之间切换和'ExitStatus.COMPLETED'在我的'checkFilesForProdTasklet' –
抱歉,我颠倒了你的任务在我的第一个swer。这个如何 ? 返回jobBuilderFactory.get( “productionOutJob”) 。开始(checkFilesForProd) 。对(ExitStatus.FAILED.getExitCode())。端() 。从(checkFilesForProd) 。对(ALL_PATTERN) 。为(productionOutStep ) .build(); 这是你期待的结果吗? – mabad
1 - ALL_PATTERN未知,是否意味着结果是什么? 2 - 我的第二个问题是如何根据业务逻辑在我的tasklet中返回ExitStatus.FAILED和ExitStatus.COMPLETED? –