gpt4 book ai didi

java - 如何在 Spring 管理中使用 JobLauncher Synchronizer

转载 作者:行者123 更新时间:2023-12-02 03:42:54 25 4
gpt4 key购买 nike

有一个@Aspect可以确保Spring Boot中的作业不可重入。它在 JobLauncherSynchronizer.java 中实现并记录here 。它位于 Spring Batch 管理工件中。

我的作业是通过 @Bean 创建的,如下所示:

@Bean
@Qualifier("synchronisationLauncher")
public JobLauncher synchronisationLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}

我的问题:
如何将@Aspect集成到我的JobLauncher中?

我天真地尝试将其更新,并在上面的方法中设置属性,毫不奇怪,效果不太好。我能够启动多个实例。

我的启动代码是:

// dependencies from constructor.
// the launcher is qualified to 'synchronisationLauncher'
private JobLauncher launcher;
private Job mergeJob;
private JobQueryHelper jobQueryHelper;

@PostMapping("uri")
public ResponseEntity<APIResponse> SynchroniseRetailers()
throws JobParametersInvalidException,
JobExecutionAlreadyRunningException,
JobRestartException,
JobInstanceAlreadyCompleteException {

JobParametersBuilder builder = new JobParametersBuilder()
.addLong("run.id", jobQueryHelper.findLastBatchExecutionIndex() + 1);
launcher.run(mergeJob, builder.toJobParameters());
return buildEmptyResponse();
}

最佳答案

您可以做的是覆盖 SimpleJobLauncher#run 方法并在运行作业之前添加双重检查:

@Bean
public JobLauncher jobLauncher(JobRepository jobRepository, JobExplorer jobExplorer) {
SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher() {
@Override
public JobExecution run(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
Set<JobExecution> running = jobExplorer.findRunningJobExecutions(job.getName());
if (!running.isEmpty()) {
throw new JobExecutionAlreadyRunningException("An instance of this job is already active: " + job.getName());
}
return super.run(job, jobParameters);
}
};
simpleJobLauncher.setJobRepository(jobRepository);
simpleJobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
simpleJobLauncher.afterPropertiesSet();
return simpleJobLauncher;
}

请注意,这与您共享的方面中的代码类似,但不需要任何类型的 AOP。正如我在评论中提到的,此检查已在 super.run(job, jobParameters) 中完成,因此我们仅在此处添加双重检查。

关于java - 如何在 Spring 管理中使用 JobLauncher Synchronizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com