JobLauncherCommandLineRunner不会在作业完成时退出

FGr*_*reg 3 java spring spring-batch

我不确定我JobLauncherCommandLineRunner是否正确使用.我正在开发一个批处理作业,它将通过命令行调用,运行完成,然后停止.它从命令行获取1个参数,我正在使用:

  • spring-boot 1.5.9
  • 春季批次3.0.8

当我通过命令行调用它时,例如:

java -Dspring.profiles.active=solr,cassandra -Dspring.config.location=/path/to/job.yml -jar myjob.jar jobParam=/path/to/file.csv
Run Code Online (Sandbox Code Playgroud)

应用程序似乎"永远"运行(至少在作业完成时).有没有配置可以在工作完成时关闭上下文?

目前我main很简单,我想保持这种方式.但也许我需要自定义逻辑来在作业完成后停止上下文?

@SpringBootApplication
public class MyJob {
    public static void main(String[] args) {
        SpringApplication.run(MyJob.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

FGr*_*reg 10

tldr;
SpringApplication.exit(context);你后SpringApplication.run你的命令main的方法.

@SpringBootApplication
public class MyJob {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(NingesterApplication.class, args);
        System.exit(SpringApplication.exit(context));
    }
}
Run Code Online (Sandbox Code Playgroud)

弄清楚了.有几个关键的事情要理解:

因此,批处理作业将在SpringApplication.run(MyJob.class, args);返回应用程序上下文之前运行完成(因为作业是上下文启动的一部分).

所以,我需要做的就是在我的应用程序类中再添加一行:

@SpringBootApplication
public class MyJob {

    private static final Logger log = LoggerFactory.getLogger(MyJob.class);

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(NingesterApplication.class, args);
        // The batch job has finished by this point because the 
        //   ApplicationContext is not 'ready' until the job is finished
        // Also, use System.exit to force the Java process to finish with the exit code returned from the Spring App
        System.exit(SpringApplication.exit(context));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,确保您使用System.exit()以确保应用程序将退出时使用与BatchStatus序数值匹配的退出代码.


旁注:因为我看到,日志有点误导

  1. 工作推出
  2. 工作完成
  3. 上下文启动
  4. 上下文关闭.

但功能上它有效:

2018-01-18 12:47:58.363  INFO 1504 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=myjob]] launched with the following parameters: [{jobParam=/path/to/file.csv}]
2018-01-18 12:47:58.399  INFO 1504 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2018-01-18 12:50:12.347  INFO 1504 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=myjob]] completed with the following parameters: [{jobParam=/path/to/file.csv}] and the following status: [COMPLETED]
2018-01-18 12:50:12.349  INFO 1504 --- [           main] g.n.j.n.ningester.NingesterApplication   : Started NingesterApplication in 136.813 seconds (JVM running for 137.195)
2018-01-18 12:50:12.350  INFO 1504 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@24313fcc: startup date [Thu Jan 18 12:47:55 PST 2018]; root of context hierarchy
Run Code Online (Sandbox Code Playgroud)