spring batch using spring boot:从配置或命令行读取参数并在作业中使用它们

spring batch using spring boot: Read arguments from config or command line and use them in job

我对 spring 技术还很陌生。我正在尝试使用 spring 批处理和 spring boot.

构建类似 ETL 的应用程序

能够运行基本作业(读取->处理->写入)。现在,我想从配置文件(稍后)或命令行(现在可以使用它)读取参数(如日期、文件名、类型等)并在我的工作中使用它们。

入口点:

// Imports
@SpringBootApplication
@EnableBatchProcessing
public class EtlSpringBatchApplication {

    public static void main(String[] args) {
        SpringApplication.run(EtlSpringBatchApplication.class, args);
    }

}

我的批量配置

// BatchConfig.java
// Imports
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public MyDao myDao;

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("job")
                .incrementer(new RunIdIncrementer())
                .listener(new Listener(myDao))
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").<myModel, myModel>chunk(1000)
                .reader(Reader.reader("my_file_20200520.txt"))
                .processor(new Processor())
                .writer(new Writer(myDao))
                .build();
    }

我有基本步骤。

Reader.java 有读取平面文件的方法。

public static FlatFileItemReader<MyModel> reader(String path) {......}

Processor.java 已定义处理方法。我添加了一个 @BeforeStep 以从处理所需的数据库中获取一些详细信息。

public class Processor implements ItemProcessor<MyModel, MyModel> {

    private static final Logger log = LoggerFactory.getLogger(Processor.class);
    private Long id = null;

    @BeforeStep
    public void getId(StepExecution stepExecution) {
        this.id = stepExecution.getJobExecution().getExecutionContext().getLong("Id");
    }

    @Override
    public MyModel process(MyModel myModel) throws Exception {
    }
}

Writer.java 正在实现 ItemWriter 并编写代码。

Listener.java 扩展了 JobExecutionListenerSupport 并覆盖了 afterJob 和 beforeJob 方法。 基本上尝试在 beforeJob 中使用 executioncontext。

@Override
public void beforeJob(JobExecution jobExecution) {
    log.info("Getting the id..");
    this.id = myDao.getLatestId();
    log.info("id retrieved is: " + this.id);
    jobExecution.getExecutionContext().putLong("Id", this.id);
}

现在,我要找的是:

简而言之,我正在寻找一种方法,

有人可以告诉我我应该在 BatchConfig.java 和其他地方做些什么,以读取作业参数(从命令行或配置文件,以容易的为准)?

您可以从 reader 内的配置文件或 spring 批处理执行上下文中的其他 classes 中读取作业参数集的值。以下是供参考的片段,

application.yml 文件可以有以下配置,

batch.configs.filePath: c:\test

您可以在启动作业时将从配置中读取的文件路径添加到您的作业参数中。 class、

的片段
// Job and Job Launcher related autowires..

@Value("${batch.configs.filePath}")
private String filePath;

// inside a method block,
JobParameters jobParameters = new JobParametersBuilder().addLong("JobID", System.currentTimeMillis())
            .addString("filePath", filePath).toJobParameters();

try {
    jobLauncher.run(batchJob, jobParameters);
} catch (Exception e) {
    logger.error("Exception while running a batch job {}", e.getMessage());
}

访问作业参数的方法之一是为您的 reader Class 实现 StepExecutionListener 以使用其覆盖的方法 beforeStep 和 afterStep。也可以对其他 classes 执行类似的实现,

public class Reader implements ItemReader<String>, StepExecutionListener {

private String filePath;

@Override
public void beforeStep(StepExecution stepExecution) {

    try {
        filePath = (String) stepExecution.getJobExecution().getExecutionContext()
                .get("filePath");
    } catch (Exception e) {
        logger.error("Exception while performing read {}", e);
    }
}


@Override
public String read() throws Exception {
    // filePath value read from the job execution can be used inside read use case impl

}

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
    return ExitStatus.COMPLETED;
}

}

Spring 批处理和 Spring 引导参考文档都显示了如何将参数传递给作业:

此外,Spring 批处理文档详细解释了如何在批处理组件(如 reader、编写器等)中使用这些参数并提供代码示例: