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

标签 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;
}

最佳答案

你可以像我一样这样做。

我假设每个作业都有一个 Spring Batch 作业配置。例如:

@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();
}

现在在你的 Controller 中,你只需 Autowiring 两个作业:

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

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

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

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

关于java - 如何选择应该在 Spring Batch + Spring Rest API 中运行的作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704657/

相关文章:

java - spring 中的动态依赖注入(inject)

java - 存储经常使用的(不可更改的)List、Map 的最佳方式是什么?

java - 参数化批量插入到Spring JDBC中

java - 使 Spring 4 Batch 服务在计划执行时可重复

java - 构建步骤时,Spring 批处理 ItemListenerSupport 的类型不明确

Java 正则表达式 : Grouping is not right

java - 在这段特定的代码中,浮点型还是整数型哪个更聪明?

java - 在空 JTextField 中按下退格键时禁用蜂鸣声

java - Android 上的 SAML

java - 带有 JPA 存储库的 Spring Boot 静态 where 子句