首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果抛出异常,则使用非零代码退出spring-batch作业

如果抛出异常,则使用非零代码退出spring-batch作业
EN

Stack Overflow用户
提问于 2016-11-05 00:31:30
回答 3查看 6.1K关注 0票数 3

我正在尝试修复一个从shell脚本启动的spring-batch作业。然后,该脚本检查进程退出代码,以确定作业是否成功。然而,即使程序以异常结束,Java也会退出0,除非使用不同的代码专门调用System.exit,因此脚本总是报告成功。

有没有办法让spring-batch在失败时返回一个非零代码?需要说明的是,我讨论的不是ExitStatus或BatchStatus,而是java进程的实际退出代码。

如果没有办法告诉spring-batch返回非零值,我能安全地在微线程(或侦听器)中使用System.exit,而不会干扰spring-batch在异常后在幕后所做的任何事情吗?

如果做不到这一点,有没有人能建议一种方法,让BatchStatus或其他失败指示器返回到shell脚本?

EN

回答 3

Stack Overflow用户

发布于 2017-11-07 22:40:36

根据this github issue,建议将SpringApplication#exit的结果传递给System#exit。您不需要直接访问ExitCodeGenerator实例或手动关闭上下文。

代码语言:javascript
复制
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
int exitCode = SpringApplication.exit(context);
System.exit(exitCode);
票数 4
EN

Stack Overflow用户

发布于 2016-11-07 17:46:53

我不建议从微线程调用System.exit(),因为作业不会完全完成,因此BATCH_-Tables中的一些条目可能会处于不一致的状态。

如果您使用类CommandLineJobRunner来启动批处理,那么将返回根据BatchStatus的返回码(可以使用SystemExiter配置CommandLineJobRunner;默认情况下,它使用一个在最后调用System.exit()的JvmSystemExiter )。但是,此解决方案绕过了SpringBoot。

因此,如果您想使用springboot,我建议您编写自己的启动包装器主-method。就像这样

代码语言:javascript
复制
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);
}
票数 2
EN

Stack Overflow用户

发布于 2017-12-07 06:44:41

我在一段时间前解决了这个问题--抱歉,我没有更快地更新。

Spring Batch确实会在失败的作业上退出非零值,但这里有一个微妙的问题。

如果作业步骤没有显式定义转换,则默认情况下,它将在成功时结束作业,在失败时使作业失败(步骤)。

但是,如果该步骤为任何结果定义了转换(例如,成功时转到下一步),则任何其他结果都没有默认转换,如果它失败了,作业将不会正常失败。因此,您必须显式地定义“失败时失败”转换(通常,对于除最后一步之外的所有步骤)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40427590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档