gpt4 book ai didi

java - 在使用 Spring Batch 和 Spring Boot 时,如何始终为每次运行启动一个新的作业实例?

转载 作者:行者123 更新时间:2023-12-02 01:51:35 25 4
gpt4 key购买 nike

在使用 Spring Batch 和 Spring Boot 时,我们将得到一个 Fat jar,其中包含我所有的 Spring Batch 作业,我希望能够通过指定作业名称从命令行触发特定作业,问题是spring batch 检测到作业已完成,因此只会运行一次作业,使用 spring boot,我们可以使用 --spring.batch.job.names=jobToRun 指定名称,问题是如何我让它始终启动一个新实例,并且仍然能够使用此机制来传递要运行的作业名称。

我没有配置JobLauncher,所以我猜它使用的是默认的JobLauncherCommandLineRunner,我当前配置的是:

@SpringBootApplication
@EnableBatchProcessing
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

通过此配置,我可以从命令行运行该作业:

java -jar batch.jar --spring.batch.job.names=job1ToRun

如何使用类似的机制为每次运行启动一个新实例?我需要从命令行指定作业名称来选择要运行的作业。

最佳答案

来自spring-batch documentation

The CommandLineJobRunner

Because the script launching the job must kick off a Java Virtual Machine, there needs to be a class with a main method to act as the primary entry point. Spring Batch provides an implementation that serves just this purpose: CommandLineJobRunner. It's important to note that this is just one way to bootstrap your application, but there are many ways to launch a Java process, and this class should in no way be viewed as definitive. The CommandLineJobRunner performs four tasks:

  • Load the appropriate ApplicationContext
  • Parse command line arguments into JobParameters
  • Locate the appropriate job based on arguments
  • Use the JobLauncher provided in the application context to launch the job.

一个非常基本的示例,说明如何执行此操作:

 public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
String jobName = args[0] // assuming args[0] is the jobName
JobParameters jobParameters = createJobParameters(args)
Job jobInstance = ctx.getBean(jobName, Job.class);
jobLauncher.run(jobInstance, jobParameters);
}

private static JobParameters createJobParameters(String[] args) {
// TODO: Create & return the needed parameters
}

关于java - 在使用 Spring Batch 和 Spring Boot 时,如何始终为每次运行启动一个新的作业实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com