11 Kasım 2018 Pazar

SpringBatch Tasklet Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
Açıklaması şöyle
The Tasklet interface has one method, execute(), which is called by the Spring Batch framework to perform the task. The execute() method must return a RepeatStatus object, which indicates whether the tasklet should be executed again.

execute metodu
İşlem sonunda RepeatStatus.FINISHED dönebilir.

Örnek
Şöyle yaparız
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.batch.core.step.tasklet.Tasklet;

@Bean
public class DeleteFileTasklet implements Tasklet {

  @Override
  public RepeatStatus execute(StepContribution contribution, 
                              ChunkContext chunkContext) throws Exception {
    File file = new File("file.txt");
    file.delete();
    return RepeatStatus.FINISHED;
  }
}


@Bean
public Step myStep(Tasklet myTasklet) {
  return stepBuilderFactory.get("deleteFileStep")
    .tasklet(deleteFileTasklet())
    .build();
}
Örnek
Şöyle yaparız.
public class HelloWorldTasklet implements Tasklet {

  @Override
  public RepeatStatus execute(StepContribution contribution, ChunkContext context)
    throws Exception {
    ...   
    return RepeatStatus.FINISHED;
  }
}
Örnek
Şöyle yaparız.
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)
 throws Exception {        
  
  if (this.isValidFile()) {
   // store the FileTypeCode in the jobExecutionContext so we can access it in other steps
    chunkContext
      .getStepContext()
      .getStepExecution()
      .getJobExecution()
      .getExecutionContext()
      .put("FileTypeCode", this.fileTypeCode);
  } else {
    throw new Exception("File '" + inputFile + "' is not a valid file format!");
  } 

  // set the exit status for the Tasklet to Completed so the overall job can get completed
  chunkContext.getStepContext().getStepExecution().setStatus(BatchStatus.COMPLETED);

  // tell Batch to continue on to the next step and not repeat this one
  return RepeatStatus.FINISHED;
}

Hiç yorum yok:

Yorum Gönder