如果抛出异常,则使用非零代码创建一个spring-batch作业出口 [英] Make a spring-batch job exit with non-zero code if an exception is thrown
问题描述
我正在尝试修复从shell脚本启动的弹出批处理作业。然后,脚本检查进程退出代码以确定作业是否成功。但是,即使程序以异常结束,Java也会退出0,除非使用不同的代码专门调用System.exit,因此脚本始终报告成功。
I'm trying to fix a spring-batch job which is launched from a shell script. The script then checks the process exit code to determine whether the job has succeeded. Java, however, exits 0 even if the program ended with an exception, unless System.exit was specifically called with a different code, so the script always reports success.
是有没有办法让spring-batch在失败时返回非零代码?要清楚,我不是在讨论ExitStatus或BatchStatus,而是java进程的实际退出代码。
Is there a way to make spring-batch return a non-zero code on failure? To be clear, I'm not talking about the ExitStatus or BatchStatus, but the actual exit code of the java process.
如果没有办法告诉spring-batch返回非零,我可以安全地在Tasklet(或监听器)中使用System.exit,而不会干扰弹出批处理后异常发生的任何事情吗?
If there's no way to tell spring-batch to return non-zero, can I safely use System.exit in a Tasklet (or a Listener) without interfering with anything that spring-batch does under the hood after an exception?
如果不这样,有人可以建议一种方法将BatchStatus或其他一些失败指示器恢复到shell脚本吗?
Failing that, can anyone suggest a way to get the BatchStatus or some other indicator of failure back to the shell script?
推荐答案
我不建议从tasklet调用System.exit(),因为作业不会完全完成,因此BATCH_-Tables中的某些条目可能会处于不一致状态。
I would not recommend calling System.exit() from a tasklet, since the job will NOT finish completely and hence some entries in BATCH_-Tables could be left in an inconsistent state.
如果使用类CommandLineJobRunner启动批处理,则返回根据BatchStatus返回的代码(CommandLineJobRunner可以配置SystemExiter;默认情况下它使用最后调用System.exit()的JvmSystemExiter )。但是,这个解决方案绕过了SpringBoot。
If you use the class CommandLineJobRunner to start your batch, then the return code according to the BatchStatus is returned (CommandLineJobRunner can be configured with an SystemExiter; as default it uses a JvmSystemExiter which calls System.exit() at the very end). However, this solution circumvents SpringBoot.
因此,如果你想使用springboot,我建议你编写自己的Launch-Wrapper main -method。类似
Therefore, if you want to use springboot, I'd recommend writing your own Launch-Wrapper main -method. Something like
public static void main(String[] args) throws Exception {
// spring boot application startup
SpringApplication springApp = new SpringApplication(.. your context ..);
// calling the run method returns the context
// pass your program arguments
ConfigurableApplicationContext context = springApp.run(args);
// spring boot uses exitCode Generators to calculate the exit status
// there should be one implementation of the ExitCodeGenerator interface
// in your context. Per default SpringBoot uses the JobExecutionExitCodeGenerator
ExitCodeGenerator exitCodeGen = context.getBean(ExitCodeGenerator.class);
int code = exitCodeGen.getExitCode();
context.close();
System.exit(code);
}
这篇关于如果抛出异常,则使用非零代码创建一个spring-batch作业出口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!