使用Tasklet在Spring Batch中删除文件,但需要退出上一步的状态

时间:2019-01-11 15:39:50

标签: java spring-boot spring-batch

我在spring批处理中有tasklet,用于删除存在的Java temp文件夹中的文件。在我的工作中,运行了主要步骤之后,我创建了一个小任务,将其删除是第二步。

要求:无论作业运行的状态为已完成还是失败,并且要保存主要步骤的状态,我都想删除该文件。

现在,会发生什么情况,如果我在作业配置中使用了next来传递tasklet,那么该文件不会被删除,以防在主要步骤中作业失败。

如果我使用步骤流来运行Tasklet(无论主要步骤是失败还是已完成),那么我将无法使用主要步骤的状态。

在示例中,步骤1下面是主要步骤,步骤3下面是tasklet

    Tasklet: 
/**
     * Tasklet execution for remove file from local directory.
     *
     * @param contribution the contribution object
     * @param chunkContext       the chunck context object
     * @return the response status
     */
    @Override
    public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) throws Exception {
        final String fileName = chunkContext.getStepContext().getJobParameters().get("fullPathFileName").toString();
        log.info("Delete the file from local directory {} ", fileName);
        boolean deleted = Files.deleteIfExists(Paths.get(fileName));
        if (!deleted) {
            throw new UnexpectedJobExecutionException("Could not delete file " + fileName);
        }
        log.info("File removed successfully");
        return RepeatStatus.FINISHED;

    }
Job Configuration With Step Flow:
public Job postalJob(ItemReader<PostalDto> postalReader) {
        return this.jobBuilderFactory.get("postalJob").incrementer(new RunIdIncrementer()).flow(step1(postalReader)).on("*").to(step3()).end().listener(batchJobListener()).build();
    }

Job Configuration without step flow:
public Job postalJob(ItemReader<PostalDto> postalReader) {
        return this.jobBuilderFactory.get("postalJob").incrementer(new RunIdIncrementer()).flow(step1(postalReader)).next(step3()).end().listener(batchJobListener()).build();
    }
Tasklet Configuration:
@Bean
    public Step step3() {
        return stepBuilderFactory.get("taskletStep").tasklet(fileDeletingTasklet()).build();
    }

如果您需要在同一方面进行更多说明,请告诉我。

0 个答案:

没有答案
相关问题