【Springboot】Springboot监听器Demo

/**
 * @author: yq
 * @date: 2020/8/31 0:01
 * @description 自定义事件
 */
@Data
public class MyEvent extends ApplicationEvent {

    private String brands;
    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public MyEvent(Object source,String brands) {
        super(source);
        this.brands=brands;

    }
}
@Slf4j
@RestController
@RequestMapping("demo")
public class MyController {

    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("test")
    public String test() {
        System.out.println("===========开始测试===========");
        System.out.println("开始发布事件");
        applicationContext.publishEvent(new MyEvent(this,"奔驰"));
        System.out.println("结束发布事件");
        System.out.println("===========结束测试===========");
        return "Success";
    }

    @EventListener
    public void accept(MyEvent event){
        System.out.println("开始监听事件");
        String brands = event.getBrands();
        System.out.println("获取事件结果 ".concat(brands));
        System.out.println("结束监听事件");
    }
}

注意使用监听器监听事件,会阻塞主线程,这里使用使用异步处理做一下优化

@Slf4j
@RestController
@RequestMapping("demo")
public class MyController {

    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("test")
    public String test() {
        System.out.println("===========开始测试===========");
        System.out.println("开始发布事件");
        applicationContext.publishEvent(new MyEvent(this,"奔驰"));
        System.out.println("结束发布事件");
        System.out.println("===========结束测试===========");
        return "Success";
    }

    @Async //异步处理的注解
    @EventListener
    public void accept(MyEvent event){
        System.out.println("开始监听事件");
        String brands = event.getBrands();
        System.out.println("获取事件结果 ".concat(brands));
        //这里睡眠4s 是为了验证主线程不会阻塞
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结束监听事件");
    }
}
@EnableAsync //注意启动类上必须加上EnableAsync注解,才能激活@Async注解
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

    }

}

 https://blog.csdn.net/weixin_42323802/article/details/84981153

原文地址:https://www.cnblogs.com/july-sunny/p/13587459.html