Spring Batch简单入门(四) - Job启动与监控

r囧r小猫 2022-05-13 07:44 610阅读 0赞

接上一章,本章我们介绍Job的启动与监听。

Running a Job

Spring Boot默认支持自动启动已配置好的Job,我们可以通过配置项**spring.batch.job.enabled=false**来禁止Spring容器自动启动Job。正常情况下,当我们通过调度器调用Job时,整个流程如下:
这里写图片描述

A JobExecution,is the primary storage mechanism for what actually happened during a run and contains many more properties that must be controlled and persisted

当Job启动之后,一个JobExecution对象会传递给Job的执行方法体,JobExecution负责存储Job执行期间执行信息,比如:状态、开始结束时间、最终退出状态、异常信息、执行上下文等等,并且最终会被传递给调用方。

  1. run job from scheduler
  2. Job [176] start 2018-09-11 15:41:41
  3. Job [176] finish 2018-09-11 15:41:42
  4. Job [176] status COMPLETED

然而,当我们试图从HTTP请求中启动Job时,我们就需要注意,Job是以异步的方式被启动,这样JobExecution会立即返回给调用者,实际Job的最后退出状态会是UNKNOWN
这里写图片描述
这是因为为批处理进程长时间保持HTTP连接并非最佳应用实践。整个流程如下图所示:
这里写图片描述

以JobLauncher启动Job

  1. @Service
  2. @Slf4j
  3. public class JobLaunchService {
  4. @Autowired
  5. private JobLauncher jobLauncher;
  6. public JobResult launchJob(Job job) {
  7. try {
  8. JobParameters jobParameters = new JobParametersBuilder()
  9. .addDate("timestamp", Calendar.getInstance().getTime())
  10. .toJobParameters();
  11. JobExecution jobExecution = jobLauncher.run(job, jobParameters);
  12. return JobResult.builder()
  13. .jobName(job.getName())
  14. .jobId(jobExecution.getJobId())
  15. .jobExitStatus(jobExecution.getExitStatus())
  16. .timestamp(Calendar.getInstance().getTimeInMillis())
  17. .build();
  18. } catch (Exception e) {
  19. log.error(e.getMessage());
  20. throw new RuntimeException("launch job exception ", e);
  21. }
  22. }
  23. }

Intercepting Job Execution

  1. public interface JobExecutionListener {
  2. void beforeJob(JobExecution jobExecution);
  3. void afterJob(JobExecution jobExecution);
  4. }

更多源码请参考:

https://github.com/ypmc/spring-cloud/tree/master/spring-batch

发表评论

表情:
评论列表 (有 0 条评论,610人围观)

还没有评论,来说两句吧...

相关阅读

    相关 spring batch

            springBatch一个轻量级,全面的批处理框架,旨在开发强大的批处理应用程序,对于企业系统的日常运营至关重要。提供可重复使用的功能,这些功能在处理大量记录