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

版权声明:请附链接,自由转载 https://blog.csdn.net/kangkanglou/article/details/82627799

上一章,本章我们介绍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执行期间执行信息,比如:状态、开始结束时间、最终退出状态、异常信息、执行上下文等等,并且最终会被传递给调用方。

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

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

以JobLauncher启动Job

@Service
@Slf4j
public class JobLaunchService {
    @Autowired
    private JobLauncher jobLauncher;

    public JobResult launchJob(Job job) {
        try {
            JobParameters jobParameters = new JobParametersBuilder()
                    .addDate("timestamp", Calendar.getInstance().getTime())
                    .toJobParameters();
            JobExecution jobExecution = jobLauncher.run(job, jobParameters);
            return JobResult.builder()
                    .jobName(job.getName())
                    .jobId(jobExecution.getJobId())
                    .jobExitStatus(jobExecution.getExitStatus())
                    .timestamp(Calendar.getInstance().getTimeInMillis())
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("launch job exception ", e);
        }
    }
}

Intercepting Job Execution

public interface JobExecutionListener {

    void beforeJob(JobExecution jobExecution);

    void afterJob(JobExecution jobExecution);

}

更多源码请参考:

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

猜你喜欢

转载自blog.csdn.net/kangkanglou/article/details/82627799