如何选择应在Spring Batch + Spring Rest API中运行的作业

时间:2019-02-15 07:44:14

标签: java spring spring-batch

我正在尝试实现2个Spring Batch作业,这些作业将在使用端点时运行。由于两者的JobLauncher方法相同,因此如何选择要执行的方法?

@Autowired
private JobLauncher jobLauncher;

@Autowired
private Job job;

@RequestMapping(
        value = "/expired",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
        params = {"expireDate"}
)
@ResponseBody
public ResponseDTO expiredJob(@RequestParam(value = "expireDate") String expireDate) throws BusinessException, Exception {

    if (!DateValidator.isDateFormatValid(expireDate)) {
        throw new BusinessException(ExceptionCodes.DATE_FORMAT_ERROR);
    }
    JobParameters jobParameters = new JobParametersBuilder().addString("expireDate", expireDate).toJobParameters();
    jobLauncher.run(job, jobParameters);

    ResponseDTO responseDTO = new ResponseDTO();

    return responseDTO;
}

@RequestMapping(
        value = "/lucky",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ResponseBody
public ResponseDTO rciplusJob() throws BusinessException, Exception {

    JobParameters jobParameters = new JobParameters();
    jobLauncher.run(job, jobParameters);

    ResponseDTO responseDTO = new ResponseDTO();

    return responseDTO;
}

1 个答案:

答案 0 :(得分:2)

您可以像我一样这样做。

我假设您为每个作业都有一个春季批处理作业配置。例如:

@Bean(name = "job1")
public Job job1() {
    return jobBuilders.get("job1")
            .incrementer(new RunIdIncrementer())
            .flow(step1())
            .end()
            .build();
}

与job2相同:

@Bean(name = "job2")
public Job job2() {
    return jobBuilders.get("job2")
            .incrementer(new RunIdIncrementer())
            .flow(step2())
            .end()
            .build();
}

现在在您的控制器中,您只需将两个作业自动连线:

@Autowired
@Qualifier("job1")
private Job job1;

@Autowired
@Qualifier("job2")
private Job job2;

要启动它们中的每一个,您可以这样操作:

final JobExecution jobExecution = jobLauncher.run(job, jobParameters);