我不确定我是否正确使用了JobLauncherCommandLineRunner
。我正在开发一个批处理作业,该作业将通过命令行调用,运行完成,然后停止。它从命令行中获取 1 个参数,我正在使用:
- 弹簧引导 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
应用程序似乎"永远"运行(至少在作业完成之后)。是否有在作业完成时关闭上下文的配置?
目前我的main
非常简单,我想保持这种状态。但是,也许我需要自定义逻辑来在作业完成后停止上下文?
@SpringBootApplication
public class MyJob {
public static void main(String[] args) {
SpringApplication.run(MyJob.class, args);
}
}
TLDR;
在main
方法中将SpringApplication.run
命令放在SpringApplication.exit(context);
之后。
@SpringBootApplication
public class MyJob {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(NingesterApplication.class, args);
System.exit(SpringApplication.exit(context));
}
}
想通了。有几个关键事项需要了解:
- BatchAutoConfiguration 会自动将 ExitCodeGenerator 注册到 JobExecutionEvents 的应用程序上下文中。
这个
ExitCodeGenerator
(特别是它是一个JobExecutionExitCodeGenerator)将从链接到JobExecutionEvent
的每个JobExecution
收集BatchStatus。JobLauncherCommandLineRunner 为其执行的每个作业发布一个
JobExecutionEvent
。JobLauncherCommandLineRunner
启动作业作为应用程序上下文启动的一部分
因此,批处理作业将在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));
}
}
然后,请确保使用System.exit()
来确保应用程序将以与BatchStatus
序号值匹配的退出代码退出。
旁注:日志有点误导,因为我看到
- 工作启动
- 作业已完成
- 上下文已启动
- 上下文关闭。
但在功能上它有效:
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