首页 > 编程语言 > 详细

【Springboot】Springboot监听器Demo

时间:2020-08-31 08:18:39      阅读:115      评论:0      收藏:0      [点我收藏+]
/**
 * @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);

    }

}

 

【Springboot】Springboot监听器Demo

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!