简体   繁体   English

Spring批量返回自定义进程退出代码

[英]Spring batch return custom process exit code

I have one jar with several jobs, I want to execute only one job each time and retrieve a custom exit code.我有一个包含多个作业的 jar,我想每次只执行一项作业并检索自定义退出代码。

For example, I have basic job ( retrieveErrorsJob ) configuration with one step that will read an input XML file and write the data in specific database table.例如,我有一个基本的作业 ( retrieveErrorsJob ) 配置,其中一个步骤将读取输入的 XML 文件并将数据写入特定的数据库表中。

Application class应用类

@SpringBootApplication
@EnableBatchProcessing
@Import(CoreCommonsAppComponent.class)
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);
    private ConfigurationConstants constants;

    @Autowired
    public Application(ConfigurationConstants constants) {
        this.constants = constants;
    }

    @EventListener(ApplicationStartedEvent.class)
    public void idApplication()
    {
        logger.info("================================================");
        logger.info(constants.APPLICATION_NAME() + "-v." + constants.APPLICATION_VERSION() + " started on " + constants.REMOTE_HOST());
        logger.info("------------------------------------------------");
    }

    public static void main(String... args) throws Exception{
        ApplicationContext context = SpringApplication.run(Application.class, args);
        logger.info("================================================");
        SpringApplication.exit(context);
    }
}

I can choose one job from command line:我可以从命令行选择一项工作:

java -jar my-jar.jar --spring.batch.job.names=retrieveErrorsJob --input.xml.file=myfile.xml

Spring Batch starts the correct job. Spring Batch 开始正确的工作。

The problem is that I need the jar to return a custom process exit integer like ExitCode.FAILED == 4 etc. But I always have a ZERO (if ExitCode = SUCCESS or FAILED).问题是我需要 jar 返回一个自定义进程退出整数,如ExitCode.FAILED == 4等。但我总是有一个零(如果 ExitCode = SUCCESS 或 FAILED)。

As per the docs, I need to implement ExitCodeMapper interface.根据文档,我需要实现ExitCodeMapper接口。

Code (not finished)代码(未完成)

public class CustomExitCodeMapper implements ExitCodeMapper {

private static final int NORMAL_END_EXECUTION = 1;
private static final int NORMAL_END_WARNING = 2;
private static final int ABNORMAL_END_WARNING = 3;
private static final int ABNORMAL_END_ERROR = 4;

@Override
public int intValue(String exitCode) {

    System.out.println("EXIT CODE = " + exitCode);

    switch (exitCode)
    {
        case "FAILED":
            return ABNORMAL_END_WARNING;
        default:
            return NORMAL_END_EXECUTION;
    }
}

} }

I can't find a way to use this custom implementation.我找不到使用此自定义实现的方法。 I could set the custom implementation to CommandLineJobRunner but how to use this class?我可以将自定义实现设置为CommandLineJobRunner但如何使用这个类?

Thanks to @Mahendra I've got an idea :)感谢@Mahendra,我有了一个想法:)

I've created a JobCompletionNotificationListener class as @Mahendra suggested:我按照@Mahendra 的建议创建了一个JobCompletionNotificationListener类:

@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {

    private static final Logger logger = LoggerFactory.getLogger(JobCompletionNotificationListener.class);

    @Override
    public void afterJob(JobExecution jobExecution) {

        SingletonExitCode exitCode = SingletonExitCode.getInstance();

       if(jobExecution.getStatus() == BatchStatus.COMPLETED)
       {
           logger.info("Exit with code " + ExitCode.NORMAL_END_OF_EXECUTION);
           exitCode.setExitCode(ExitCode.NORMAL_END_OF_EXECUTION);
       }
       else {
           logger.info("Exit with code " + ExitCode.ABNORMAL_END_OF_EXECUTION_WARNING);
           exitCode.setExitCode(ExitCode.ABNORMAL_END_OF_EXECUTION_WARNING);
       }
    }
}

But I don't force the application to exit with System.exit() from this class.但是我不会强制应用程序从这个类中使用System.exit()退出。 I've implemented a simple singleton like this:我已经实现了这样一个简单的单例:

public class SingletonExitCode {

    public ExitCode exitCode = ExitCode.ABNORMAL_END_OF_EXECUTION_WARNING; // Default code 3
    private static SingletonExitCode instance = new SingletonExitCode();

    private SingletonExitCode() {}

    public static SingletonExitCode getInstance() {
        return instance;
    }

    public void setExitCode(ExitCode exitCode) {
        this.exitCode = exitCode;
    }
}

and I ask the ExitCode from my singleton after closing Spring context:在关闭 Spring 上下文后,我从我的单例中询问ExitCode

@SpringBootApplication
@EnableBatchProcessing
@Import(CoreCommonsAppComponent.class)
public class Application {
    // a lot of nice things

    public static void main(String... args) throws Exception{
        ApplicationContext context = SpringApplication.run(Application.class, args);
        logger.info("================================================");
        SpringApplication.exit(context);
        System.exit(SingletonExitCode.getInstance().exitCode.getCode());
    }
}

I did this because if we exit directly from JobCompletionNotificationListener class we miss an important line in the logs:我这样做是因为如果我们直接从JobCompletionNotificationListener类退出,我们会错过日志中的重要一行:

Job: [FlowJob: [name=writeErrorFromFile]] completed with the following parameters: [{-input.xml.file=c:/temp/unit-test-error.xml, -spring.batch.job.names=writeErrorFromFile, run.id=15, input.xml.file=c:/temp/unit-test-error.xml}] and the following status: [FAILED]作业:[FlowJob: [name=writeErrorFromFile]] 使用以下参数完成:[{-input.xml.file=c:/temp/unit-test-error.xml, -spring.batch.job.names=writeErrorFromFile, run.id=15, input.xml.file=c:/temp/unit-test-error.xml}] 和以下状态:[FAILED]

And seems that Spring context is not properly closed.并且似乎 Spring 上下文没有正确关闭。

Despite of exit-status of Sprint-Batch's Job (ie COMPLETED or FAILED), java process will be completed successfully (and you will get process exit-code as 0).尽管 Sprint-Batch 的作业退出状态(即 COMPLETED 或 FAILED),java 进程将成功完成(并且您将获得进程退出代码为 0)。

If you want a custom exit-code for java process so that you can use it any script or somewhere else, you can use JobExecutionListener .如果您想要一个 Java 进程的自定义退出代码,以便您可以在任何脚本或其他地方使用它,您可以使用JobExecutionListener

You can check the job's exitStatus in afterJob() and accordingly exit the java process with your desired exit-code (ie 4 for FAILURE)您可以在afterJob()检查作业的 exitStatus 并相应地使用所需的退出代码退出 java 进程(即 4 表示 FAILURE)

Example of JobExecutionListener JobExecutionListener 示例

public class InterceptingExitStatus implements JobExecutionListener{

    @Override
    public void beforeJob(JobExecution jobExecution) {
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        ExitStatus exitStatus = jobExecution.getExitStatus() ;

        if(exitStatus == ExitStatus.COMPLETED ){
            System.exit(0);
        }

        if(exitStatus == ExitStatus.FAILED ){
            System.exit(4);
        }
    }

}

and this is how you can configure job-listener in the xml file -这就是您可以在 xml 文件中配置作业侦听器的方法 -

<job id="job">
....
....

    <listeners>
        <listener ref="interceptingExitStatus "/>
    </listeners>
</job>

Spring Boot and Sring Batch already have an internal solution for this, all you need is an extra line of code: Spring Boot 和 Sring Batch 已经有一个内部解决方案,你只需要额外的一行代码:

System.exit(SpringApplication.exit(applicationContext));

Here is another example:这是另一个例子:

public class BatchApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(BatchApplication.class, args);
        System.exit(SpringApplication.exit(applicationContext));
    }

}

EDIT: If you would like to know how it works check this class: org.springframework.boot.autoconfigure.batch.JobExecutionExitCodeGenerator编辑:如果你想知道它是如何工作的,请检查这个类:org.springframework.boot.autoconfigure.batch.JobExecutionExitCodeGenerator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM