spring batch 监听器(监听job , step)

2020-04-27  本文已影响0人  刘小刀tina

针对job step 监听拦截功能的实现有两种:
(1): 实现接口 重写其中的方法;
(2):用注解的方法。@AfterJob@AfterStep

1 . 监听器 (job , step)

/**
 * @program: demo-spring-batch
 * @description
 *  集成接口的方式设置监听Job的监听器
 * @author: tina.liu
 * @create: 2020-04-27 18:36
 **/
public class ListenerJobDemo implements JobExecutionListener {
    @Override
    public void beforeJob(JobExecution jobExecution) {

        System.out.println("监听器监听Job之前,job的名字为:"+jobExecution.getJobInstance().getJobName());

    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        System.out.println("监听器监听Job之后,job的名字为:"+jobExecution.getJobInstance().getJobName());
    }

}
======================================================
/**
 * @program: demo-spring-batch
 * @description
 *   利用注解的方法 配置监听step的监听器
 * @author: tina.liu
 * @create: 2020-04-27 18:39
 **/
public class Listenerstepchunk {

    @BeforeChunk
    public void beforeChunk(ChunkContext context){
        System.out.println("监听器监听step之前,step的名字为:"+context.getStepContext().getStepName());

    }


    @AfterChunk
    public void afterChunk(ChunkContext context){
        System.out.println("监听器监听step之后,step的名字为:"+context.getStepContext().getStepName());

    }
}

======================================================
@Configuration
@EnableBatchProcessing
public class ListenerDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory ;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean(value = "listenerDemoJob1")
    public Job listenerDemoJob1(){
        return jobBuilderFactory.get("listenerDemoJob1")
                .start(listenerDemostep2())
                .listener(new ListenerJobDemo())
                .build();
    }

    /**
     * 创建step
     * @return
     */
    @Bean(value = "listenerDemostep2")
    public Step listenerDemostep2(){
        return stepBuilderFactory.get("listenerDemostep2")
                .<String,String>chunk(2)
                .faultTolerant()
                .listener(new Listenerstepchunk())
                .reader(read())
                .writer(writer())
                .build();

    }

    @Bean
    public ItemWriter<? super String> writer() {
        return new ItemWriter<String>() {
            @Override
            public void write(List<? extends String> list) throws Exception {
                for (String str:list) {
                    System.out.println("str的值为"+str);
                }
            }
        };
    }

    @Bean
    public ItemReader<? extends String> read() {
        return new ListItemReader<>(Arrays.asList("java","spring","mybatis","mysql"));
    }

}
======================================================
上一篇下一篇

猜你喜欢

热点阅读