简体   繁体   中英

How to count items in a Tasket in spring-batch?

I have a Tasklet and want to count the items processed. Then a common StepExecutionListener should be able to read those processed item count in afterStep() :

@Bean
public Step myStep() {
    return stepBuilderFactory.get("Step2")
            .tasklet(new Tasklet() {
                @Override
                public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                    int items = dao.deleteItems(); //how to pass these items to a StepExecutionListener?
                    return RepeatStatus.FINISHED;
                }
            })
            .build();


@Component
public class MyListener extends StepExecutionListenerSupport {
    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        long items = stepExecution.getWriteCount();
        return super.afterStep(stepExecution);
    }
}

How can I get the processed items into the stepExecution within the tasklet?

There are two ways to do that:

  • Increment the write count from the StepContribution with contribution.incrementWriteCount(items);
  • Set the write count from the StepExecution . You can access the StepExecution from the current ChunkContext . You need to call getStepContext() to retrieve the StepContext , then call getStepExecution() to retrieve the StepExecution and finally, you can set the write count with setWriteCount(writeCount) .

A sample code would be:

public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    int items = dao.deleteItems();
    contribution.incrementWriteCount(items);
    // OR: chunkContext.getStepContext().getStepExecution().setWriteCount(items);
    return RepeatStatus.FINISHED;
}

As you are using a tasklet and not a chunk, the classic "read/process/write" does not apply. If you want to transfer a value from your step execution to a stepExecutionListener on the same step, then simply put a key/value in your stepExecutionContext:

   int items=dao.deleteItems();
   chunkContext.getStepContext().getStepExecution().getExecutionContext().putInt("MYKEY", items);

In your StepExecutionListener afterStep(StepExecution stepExecution) method:

ExecutionContext executionContext = stepExecution.getExecutionContext();
int items = executionContext.getInt("MYKEY");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM