如何重新启动已停止的 Spring 批处理作业
how to restart a Stopped Spring Batch job
@GetMapping("/stopjob")
public void stop() throws Exception{
Set<Long> executions = jobOperator.getRunningExecutions("LoadData");
jobOperator.stop(executions.iterator().next());
}
@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
jobRegistry.register(new ReferenceJobFactory(job));
jobOperator.restart(id); // (1)
}
停止工作正常,但恢复工作只是在 运行 项目后第一次工作,如果我再次调用此方法,我会得到此执行
org.springframework.batch.core.configuration.DuplicateJobException: 已注册具有此名称 [LoadData] 的作业配置
任何解决方案!
这是因为您每次都在 restart
方法中调用 jobRegistry.register(new ReferenceJobFactory(job));
,而这通常只调用一次。
因此您需要像这样从方法中删除该调用:
@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
jobOperator.restart(id); // (1)
}
并将作业注册移动到一个只在您的 Web 控制器初始化时调用一次的方法,例如通过使用带有 @PostConstruct
注释的方法或使您的控制器实现 InitializingBean#afterPropertiesSet
。这是带有 @PostConstruct
注释的示例:
@PostConstruct
public void registerJob() {
jobRegistry.register(new ReferenceJobFactory(job));
}
@GetMapping("/stopjob")
public void stop() throws Exception{
Set<Long> executions = jobOperator.getRunningExecutions("LoadData");
jobOperator.stop(executions.iterator().next());
}
@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
jobRegistry.register(new ReferenceJobFactory(job));
jobOperator.restart(id); // (1)
}
停止工作正常,但恢复工作只是在 运行 项目后第一次工作,如果我再次调用此方法,我会得到此执行
org.springframework.batch.core.configuration.DuplicateJobException: 已注册具有此名称 [LoadData] 的作业配置
任何解决方案!
这是因为您每次都在 restart
方法中调用 jobRegistry.register(new ReferenceJobFactory(job));
,而这通常只调用一次。
因此您需要像这样从方法中删除该调用:
@GetMapping("/resumejob/{id}")
public void restart(@PathVariable(name = "id") long id) throws Exception {
jobOperator.restart(id); // (1)
}
并将作业注册移动到一个只在您的 Web 控制器初始化时调用一次的方法,例如通过使用带有 @PostConstruct
注释的方法或使您的控制器实现 InitializingBean#afterPropertiesSet
。这是带有 @PostConstruct
注释的示例:
@PostConstruct
public void registerJob() {
jobRegistry.register(new ReferenceJobFactory(job));
}