Storing in JobExecutionContext from tasklet and accessing in another tasklet

前端 未结 2 1204
梦毁少年i
梦毁少年i 2020-12-01 01:45

I have a requirement in which a tasklet, stores all the files in the directories in an arraylist. The size of the list is stored in the job execution context. Later this cou

2条回答
  •  情深已故
    2020-12-01 02:11

    you have at least 4 possibilities:

    1. use the ExecutionPromotionListener to pass data to future steps
    2. use a (spring) bean to hold inter-step data, e.g. a ConcurrentHashMap
      • without further action this data won't be accessible for a re-start
    3. access the JobExecutionContext in your tasklet, should be used with caution, will cause thread problems for parallel steps
    4. use the new jobscope (introduced with spring batch 3)

    Code Example for accessing JobExecution from Tasklet:

    1. setting a value

      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;
          }
      
      }
      
    2. extracting a value

      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;
          }
      }
      

    i created code examples for the first 3 solutions in my spring-batch-examples github repository, see module complex and package interstepcommunication

提交回复
热议问题