【发布时间】:2018-07-11 17:31:01
【问题描述】:
我正在尝试在作业完成之前返回 Spring Batch 作业 ID。
我当前的实现只在作业完成后返回信息 完成。
我使用批处理程序控制器和批处理服务,发布在下面。 谢谢,我是 Spring Batch 的新手,经过详尽的搜索 找不到与我的问题相关的太多内容。有一个帖子 有人使用 Apache Camel,但我不是。
- 我知道 SimpleAsyncTaskExecutor(),但不知道如何在这里应用它
控制器
@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET)
public ResponseEntity<JobResults> process(@PathVariable("progName") String progName,
@RequestHeader("Accept") MediaType accept) throws Exception {
HttpHeaders responseHeaders = MccControllerUtils.createCacheDisabledHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_XML);
if(!accept.toString().equals("*/*")) {
responseHeaders.setContentType(accept);
}
LOGGER.info("Running batch program " + progName);
JobResults response = batchService.processProgName(progName);
return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
}
服务
@Override
public JobResults processProgName(String progName) throws Exception {
String jobName = "call" + progName.toUpperCase() + "Job";
JobExecution jobExecution = null;
String result = "";
Long jobId = null;
JobResults results = new JobResults();
BatchStatus jobStatus = null;
try {
// Launch the appropriate batch job.
Map<String, Job> jobs = applicationContext.getBeansOfType(Job.class);
LOGGER.info("BATCHSTART:Starting sync batch job:" + jobName);
JobParametersBuilder builder = new JobParametersBuilder();
// Pass in the runtime to ensure a fresh execution.
builder.addDate("Runtime", new Date());
jobExecution = jobLauncher.run(jobs.get(jobName), builder.toJobParameters());
jobId = jobExecution.getId();
jobStatus = jobExecution.getStatus();
results.setName(jobName);
results.setId(jobId);
results.setMessage("The job has finished.");
results.setStatus(jobStatus);
LOGGER.info("The job ID is " + jobId);
LOGGER.info("BATCHEND:Completed sync batch job:" + jobName);
LOGGER.info("Completion status for batch job " + jobName + " is " + jobExecution.getStatus().name());
List<Throwable> failures = jobExecution.getAllFailureExceptions();
if (failures.isEmpty()) {
result = jobExecution.getExecutionContext().getString(AbstractSetupTasklet.BATCH_PROGRAM_RESULT);
} else {
for (Throwable fail : failures) {
result += fail.getMessage() + "\n";
}
}
LOGGER.info("The job results are: " + result);
} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
throw new RuntimeException("An error occurred while attempting to execute a job. " + e.getMessage(), e);
}
return results;
}
再次感谢。
编辑
我已将此添加到我的批处理配置中
@Bean(name = "AsyncJobLauncher")
public JobLauncher simpleJobLauncher(JobRepository jobRepository){
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return jobLauncher;
}
编辑
我在 Mahmoud Ben Hassine 的评论的帮助下解决了这个问题 :)
我不得不从服务中删除结果变量和信息,并添加上面看到的代码。当我现在到达终点时,我会立即收到工作信息。
【问题讨论】:
标签: spring-boot asynchronous spring-batch