简体   繁体   English

spring 批处理使用 spring 启动:从配置或命令行读取 arguments 并在作业中使用它们

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

I am pretty new to spring technology.我对 spring 技术很陌生。 I am trying to build an ETL like app using spring batch with spring boot.我正在尝试使用 spring 批处理和 spring 启动构建类似 ETL 的应用程序。

Able to run the basic job (read->process->write).能够运行基本作业(读取->处理->写入)。 Now, I want to read the arguments (like date, file name, type, etc) from a config file (later) or command line (can work with it now) and use them in my job.现在,我想从配置文件(稍后)或命令行(现在可以使用它)中读取 arguments(如日期、文件名、类型等)并在我的工作中使用它们。

Entry point:入口点:

// Imports
@SpringBootApplication
@EnableBatchProcessing
public class EtlSpringBatchApplication {

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

}

My batch configuration我的批处理配置

// 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();
    }

I have basic steps steps.我有基本的步骤步骤。

Reader.java has method to read flat file. Reader.java 有读取平面文件的方法。

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

Processor.java has process method defined. Processor.java 已定义处理方法。 I added a @BeforeStep to fetch some details from DB required for processing.我添加了一个@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 is implementing ItemWriter and write code. Writer.java 正在实现 ItemWriter 并编写代码。

Listener.java extends JobExecutionListenerSupport and has overridden methods afterJob and beforeJob. Listener.java 扩展了 JobExecutionListenerSupport 并覆盖了 afterJob 和 beforeJob 方法。 Basically tried to use executioncontext here in 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);
}

Now, what I am looking for is:现在,我正在寻找的是:

  • The reader should get the file name from job arguments.读者应该从作业 arguments 中获取文件名。 ie when run the job, I should be able to give some arguments, one of them is file path.即在运行作业时,我应该能够提供一些 arguments,其中之一是文件路径。
  • Later some methods (like get id, etc) require few more variables which can be passed as arguments to job ie run_date, type, etc.稍后一些方法(如获取 id 等)需要更多的变量,这些变量可以作为 arguments 传递给作业,即 run_date、类型等。

In short I am looking for a way to,简而言之,我正在寻找一种方法,

  • Pass job arguments to my app (run_date, type, file path etc)将作业 arguments 传递给我的应用程序(运行日期、类型、文件路径等)
  • Use them in reader and other places (Listener, Writer)在阅读器和其他地方使用它们(听众,作家)

Can someone provide me what addiitons I should do in my BatchConfig.java and other places, to read the job parameters (from command line or config file, whichever is easy)?有人可以提供我应该在我的 BatchConfig.java 和其他地方做些什么来读取作业参数(从命令行或配置文件,以容易的为准)吗?

You can read the value of the of the job parameters set from the config file inside the reader or other classes within the spring batch execution context.您可以从阅读器内的配置文件或 spring 批处理执行上下文中的其他类中读取作业参数集的值。 Below is a snippet for reference,下面是一个片段供参考,

application.yml file can have the below config, application.yml 文件可以有以下配置,

batch.configs.filePath: c:\test

You can add the filePath read from the config to your job parameters when you start the job.您可以在启动作业时将从配置中读取的 filePath 添加到作业参数中。 Snippet of the class, 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());
}

One of the ways to access the Job Parameters is to implement StepExecutionListener to your reader Class to make use of its Overridden methods beforeStep and afterStep.访问作业参数的一种方法是对您的阅读器 Class 实施 StepExecutionListener,以利用其覆盖的方法 beforeStep 和 afterStep。 Similar implementations can be performed to other classes as well,也可以对其他类执行类似的实现,

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

} }

Both Spring Batch and Spring Boot reference documentation show how to pass parameters to a job: Spring Batch 和 Spring 引导参考文档都显示了如何将参数传递给作业:

Moreover, Spring Batch docs explain in details and with code examples how to use those parameters in batch components (like reader, writer, etc):此外,Spring 批处理文档详细解释了如何在批处理组件(如读取器、写入器等)中使用这些参数并附有代码示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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