如何从 TASKLET 中的执行方法获取 Spring 批处理作业实例 ID

how to get Spring Batch job instance id from execute method in TASKLET

我正在使用 Spring Batch 3.0 版本的布局。

通过执行 TASKLET 的 JobLauncher 运行 方法创建一个 Job 并执行放置。

我想通过在TASKLET中查询插入逻辑,对应的JobId和metatables之外的其他表,更准确的知道Job是否被执行

public class SampleScheduler {

protected final Logger log = LoggerFactory.getLogger(this.getClass());

@Autowired
private JobLauncher jobLauncher;

@Autowired
private Job sampleJob;

public void run() {
    try {
        String dateParam = new Date().toString();
        JobParameters param = new JobParametersBuilder().addString("date",dateParam).toJobParameters();
        JobExecution execution = jobLauncher.run(sampleJob, param);

        log.debug("###################################################################");
        log.debug("Exit Status : " + execution.getStatus());
        log.debug("###################################################################");

    } catch (Exception e) {
        // e.printStackTrace();
        log.error(e.toString());
    }
}   
}

调用tasklet的代码-

public class SampleTasklet implements Tasklet{

@Autowired
private SampleService sampleService;

@Override
public RepeatStatus execute(StepContribution contribution,
        ChunkContext chunkContext) throws Exception {

    sampleService.query();

    return RepeatStatus.FINISHED;
    }
}

这是我的 tasklet 代码。

    StepContext stepContext = chunkContext.getStepContext();
    StepExecution stepExecution = stepContext.getStepExecution();
    JobExecution jobExecution = stepExecution.getJobExecution();
    long jobInstanceId = jobExecution.getJobId();

在上面的 TASKLET 代码中尝试这样做是否正确?

how to get Spring Batch job instance id from execute method in TASKLET

org.springframework.batch.core.step.tasklet.Tasklet#execute 方法使您可以访问 ChunkContext,后者又允许您获取父级 StepExecutionJobExecution。然后您可以从作业执行中获取作业实例 ID。

Is it right to try this in the TASKLET code above?

是的,就是这样。