一尘不染

从Tasklet存储在JobExecutionContext中并在另一个Tasklet中访问

spring

我需要一个tasklet,将所有文件存储在arraylist目录中。列表的大小存储在作业执行上下文中。稍后,可以在另一个步骤中从另一个Tasklet访问此计数。它是如何做到的。我试图将其存储在jobexecution上下文中,在运行时抛出无法修改的集合异常,

public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
throws Exception {
    StepContext stepContext = arg1.getStepContext();
    StepExecution stepExecution = stepContext.getStepExecution();
    JobExecution jobExecution = stepExecution.getJobExecution();
    ExecutionContext jobContext = jobExecution.getExecutionContext();
     jobContext.put("FILE_COUNT",150000);

还在步骤注释中存储了步骤执行参考。仍然无法实现。请让我知道如何在两个小任务之间共享数据。


阅读 611

收藏
2020-04-19

共1个答案

一尘不染

你至少有4种可能性:

  1. 使用ExecutionPromotionListener 将数据传递到以后的步骤
  2. 使用(spring)bean来保存步间数据,例如ConcurrentHashMap
    如果不采取进一步措施,该数据将无法重新启动
  3. 访问你的tasklet中的JobExecutionContext,应谨慎使用,这将导致并行步骤出现线程问题
  4. 使用新的jobscope(引入的弹簧批次3)
    从Tasklet访问JobExecution的代码示例:

设定值

public class ChangingJobExecutionContextTasklet implements Tasklet {

    /** {@inheritDoc} */
    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        // set variable in JobExecutionContext
        chunkContext
                .getStepContext()
                .getStepExecution()
                .getJobExecution()
                .getExecutionContext()
                .put("value", "foo");

        // exit the step
        return RepeatStatus.FINISHED;
    }

}

提取值

public class ReadingJobExecutionContextTasklet implements Tasklet {

    private static final Logger LOG = LoggerFactory.getLogger(ChangingJobExecutionContextTasklet.class);

    /** {@inheritDoc} */
    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        // pull variable from JobExecutionContext
        String value = (String) chunkContext
                                    .getStepContext()
                                    .getStepExecution()
                                    .getJobExecution()
                                    .getExecutionContext()
                                    .get("value");

        LOG.debug("Found value in JobExecutionContext:" + value);

        // exit the step
        return RepeatStatus.FINISHED;
    }
}
2020-04-19