如何限制Spring Batch作业的多个实例运行?

问题描述 投票:0回答:2

我的 Spring 批次是由 Rest 端点触发的。我正在寻找一次仅运行一个作业实例的解决方案。

spring spring-batch
2个回答
1
投票

您可以实现一个重写 beforeJob 方法的侦听器,该方法将在作业启动之前运行并检查同一作业的另一个实例是否正在运行。如果另一个实例已经在运行,它将停止当前运行。

@Component
public class MultipleCheckListener implements JobExecutionListener {
    @Autowired
    private JobExplorer explorer;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        String jobName = jobExecution.getJobInstance().getJobName();
        Set<JobExecution> executions = explorer.findRunningJobExecutions(jobName);
        if(executions.size() > 1) {
            jobExecution.stop();
        }
    }    
}

0
投票

如何停止执行并使用上面的监听器

@Bean
public Job JobSE(JobRepository jobRepository, JobExecutionListener jobExecutionListener)
    throws UnexpectedInputException, ParseException {
    return new JobBuilder(CUSTOMER_REPORT_JOB_SE, jobRepository)
        .start((Step) applicationContext.getBean("jobSEStep"))
        .preventRestart()
        .listener(jobExecutionListener)
        .build();
}
@Bean
@Scope("prototype")
public JobExecutionListener jobExecutionListener(JobExplorer explorer, JobOperator jobOperator) {
    return new JobExecutionListener() {
        @Override
        public void beforeJob(@NonNull JobExecution jobExecution) {
            String jobName = jobExecution.getJobInstance().getJobName();
            Set<JobExecution> executions = explorer.findRunningJobExecutions(jobName);
            if (executions.size() > 1) {
                try {
                    jobOperator.stop(jobExecution.getId());
                    jobExecution.setStatus(BatchStatus.STOPPED);
                } catch (NoSuchJobExecutionException | JobExecutionNotRunningException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.