我正在使用 Spring Batch 5.1.2 并遇到一个问题,即我的步骤被执行多次(正好 5 次),即使我只希望它执行一次。当我将 TaskExecutor 添加到步骤配置时,会发生这种情况。 这是我的步骤配置:
@Bean("dynamicStep0")
public Step dynamicStep0() {
return new StepBuilder("step1Tasklet", jobRepository)
.tasklet(new Step0Tasklet(), transactionManager)
.taskExecutor(dynamicBatchStepExecutor())
.build();
}
我的任务执行器配置:
@Bean("dynamicBatchStepTaskExecutor")
public ThreadPoolTaskExecutor dynamicBatchStepExecutor() {
ThreadPoolTaskExecutor tpe = new ThreadPoolTaskExecutor();
tpe.setCorePoolSize(1);
tpe.setMaxPoolSize(1);
tpe.setThreadNamePrefix("DynamicSteps-JOB-EXEC-");
tpe.initialize();
return tpe;
}
Tasklet 实现:
@RequiredArgsConstructor
@Slf4j
@StepScope
public class Step0Tasklet implements Tasklet {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
log.info("Step0Tasklet executed, this is a dummy step");
return RepeatStatus.FINISHED;
}
}
输出日志当我运行作业时,我看到该步骤被执行了 5 次:
[INFO] SimpleJobLauncher [] - Job: [SimpleJob: [name=Dynamic job 2]] launched with the following parameters: [{'jobId':'{value=1736954208659, type=class java.lang.Long, identifying=true}'}]
[INFO] SimpleStepHandler [] - Executing step: [step1Tasklet]
[INFO] DynamicSteps-JOB-EXEC-1 Step0Tasklet [] - Step0Tasklet executed, this is a dummy step
[INFO] DynamicSteps-JOB-EXEC-1 Step0Tasklet [] - Step0Tasklet executed, this is a dummy step
[INFO] DynamicSteps-JOB-EXEC-1 Step0Tasklet [] - Step0Tasklet executed, this is a dummy step
[INFO] DynamicSteps-JOB-EXEC-1 Step0Tasklet [] - Step0Tasklet executed, this is a dummy step
[INFO] DynamicSteps-JOB-EXEC-1 Step0Tasklet [] - Step0Tasklet executed, this is a dummy step
.taskExecutor(dynamicBatchStepExecutor())
.throttleLimit(1)
tpe.setQueueCapacity(1);
问题
环境
任务执行器用于并行处理块,而不是一次性执行步骤 https://docs.spring.io/spring-batch/reference/scalability.html 如果删除它,它将执行一次。