Spring批处理限制跨多个服务器的单个作业实例

Jos*_*osh 5 java spring spring-batch spring-boot

我有一个 Spring Batch 作业可能会在多台服务器上运行。我有一个监听器,可以防止在一台服务器上同时运行多个作业实例。但是,我想确保此作业不能在多台服务器上同时运行。

我已经搜索并没有找到解决此问题的方法

Jos*_*osh 6

我实现了一个侦听器,用于检查匹配特定名称的 spring 批处理控制表中正在运行的作业执行的数量。如果执行的大小超过 1,则当前作业的 jobExecution 失败。这是代码:

@Component
public class SingleInstanceListener 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();
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }

}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,如果批处理持久性存储是数据库,则“未知”状态下的单次执行将阻止批处理再次执行。值得在时间限制内测试执行,或使用自定义清理代码来删除有毒的“未知”执行。 (3认同)