美文网首页
spring batch-->JobLauncher启动job

spring batch-->JobLauncher启动job

作者: 刘小刀tina | 来源:发表于2020-04-28 11:41 被阅读0次
/**
 * @program: demo-spring-batch
 * @description: 利用JobLauncher启动job 传递参数完成作业
 * @author: tina.liu
 * @create: 2020-04-28 11:16
 **/
@Configuration
@EnableBatchProcessing
public class JobLauncherDemo implements StepExecutionListener{

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;


    private Map<String, JobParameter> parameters;

    @Bean(value = "jobLauncherDemoJob")
    public Job jobLauncherDemoJob(){
        return jobBuilderFactory.get("jobLauncherDemoJob")
                .start(jobLauncherDemoStep())
                .build();
    }

    @Bean(value = "jobLauncherDemoStep")
    public Step jobLauncherDemoStep() {
        return stepBuilderFactory.get("jobLauncherDemoStep")
                .listener(this)
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                        System.out.println("传递de参数值为:"+parameters.get("msg").getValue());
                        return RepeatStatus.FINISHED;
                    }
                }).build();
    }


    /**
     * 利用step监听器将参数赋值到step
     * @param stepExecution
     */
    @Override
    public void beforeStep(StepExecution stepExecution) {

        parameters = stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}


@RestController
class JobLauncherController{

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job jobLauncherDemoJob;

    @GetMapping(value = "/job/{msg}")
    public String jobRun1(@PathVariable String msg){
        //将接受的参数传递给任务
        JobParameters parameters = new JobParametersBuilder()
                .addString("msg",msg)
                .toJobParameters();
        //启动任务 并把参数传给任务
        try {
            jobLauncher.run(jobLauncherDemoJob,parameters);
        } catch (JobExecutionAlreadyRunningException e) {
            e.printStackTrace();
            System.out.println("出现异常"+e.getMessage());
        } catch (JobRestartException e) {
            e.printStackTrace();
            System.out.println("出现异常"+e.getMessage());
        } catch (JobInstanceAlreadyCompleteException e) {
            e.printStackTrace();
            System.out.println("出现异常"+e.getMessage());
        } catch (JobParametersInvalidException e) {
            e.printStackTrace();
            System.out.println("出现异常"+e.getMessage());
        }
        return "job success";
    }
}

相关文章

网友评论

      本文标题:spring batch-->JobLauncher启动job

      本文链接:https://www.haomeiwen.com/subject/sykvwhtx.html