Batch
本节将详细介绍 Spring Cloud Task 与 Spring Batch 的集成。跟踪作业执行与执行该作业的任务之间的关联关系。
将作业执行关联到其执行所在的任务
Spring Boot 提供了在 Spring Boot Uber-jar 中执行批处理作业的功能。Spring Boot 对此功能的支持允许开发人员在该执行中运行多个批处理作业。Spring Cloud Task 提供了将作业执行(job execution)与任务执行(task execution)关联起来的能力,以便可以从一个追溯到另一个。
Spring Cloud Task 通过使用 TaskBatchExecutionListener 来实现此功能。默认情况下,在任何配置了 Spring Batch Job(通过在上下文中定义类型为 Job 的 bean)且类路径上存在 spring-cloud-task-batch jar 的上下文中,此监听器都会自动配置。该监听器会被注入到所有满足这些条件的作业中。
重写 TaskBatchExecutionListener
为了防止监听器被注入到当前上下文中的任何批处理作业中,你可以使用标准的Spring Boot机制来禁用自动配置。
若仅需在特定作业的上下文中注入监听器,请重写 batchTaskExecutionListenerBeanPostProcessor 并提供一个作业 Bean ID 列表,如下例所示:
public static TaskBatchExecutionListenerBeanPostProcessor batchTaskExecutionListenerBeanPostProcessor() {
TaskBatchExecutionListenerBeanPostProcessor postProcessor =
new TaskBatchExecutionListenerBeanPostProcessor();
postProcessor.setJobNames(Arrays.asList(new String[] {"job1", "job2"}));
return postProcessor;
}
你可以在 Spring Cloud Task 项目的示例模块中找到批处理应用程序的示例,点击此处查看。
批量信息消息
Spring Cloud Task 为批处理作业提供了发送信息性消息的能力。有关此功能的详细信息,请参阅“Spring Batch 事件”部分。
批处理作业退出代码
正如之前所讨论的,Spring Cloud Task 应用程序支持记录任务执行的退出码。然而,当你在任务中运行 Spring Batch Job 时,无论 Batch Job 执行如何完成,使用默认的 Batch/Boot 行为时,任务的结果始终为零。请记住,任务是一个 Boot 应用程序,从任务返回的退出码与 Boot 应用程序相同。为了覆盖此行为,并允许在批处理作业返回 FAILED 的 BatchStatus 时,任务返回非零的退出码,请将 spring.cloud.task.batch.fail-on-job-failure 设置为 true。然后退出码可以是 1(默认值)或基于指定的 ExitCodeGenerator。
此功能使用了一个新的 ApplicationRunner,它替代了 Spring Boot 提供的默认实现。默认情况下,其执行顺序与 Spring Boot 的默认顺序相同。然而,如果您想自定义 ApplicationRunner 的执行顺序,可以通过设置 spring.cloud.task.batch.applicationRunnerOrder 属性来调整其顺序。若希望任务根据批处理作业的执行结果返回退出码,您需要编写自己的 CommandLineRunner。