Spring boot的监听这么简单?

Posted NewWorldForU

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot的监听这么简单?相关的知识,希望对你有一定的参考价值。

Spring 的监听这么简单?

需求

当接收msg = 6667时,除了原有逻辑外,还需记录日志,且处理其他复杂业务事件。

技术选型

监听器,优势其一,该业务是一个复杂业务逻辑,耗时,若同步执行则会导致用户体验极差。其二:服务解耦。

其实监听器最主要的就是为了服务解耦,类似一些日志、发邮件、发短信等等业务操作都可以运用监听器处理。
Spring中AlpplicationContext 对象(上下文对象)中提供了publishEvent()方法,实现了观察者设计模式,可以通过ApplicationEvent传播给系统中所有的监听者。

ApplicationEvent:被监听的事件对象。
Listener:观察者,可实现多个。

实现

核心事件类 ApplicationEvent

public class MyApplicationEvent extends ApplicationEvent 

    public String msg;

    public MyApplicationEvent(Object source, String msg) 
        super(source);
        this.msg = msg;
    

Spring 中有俩种实现监听器的方式,ApplicationListener 和 @EventListener
@EventListener中condition为EL表达式,

@Slf4j
@Component
public class MyApplicationLister1 

    // 同步的
    @EventListener(condition = "#event.msg.equals('6667')")
    public void testA(MyApplicationEvent event) 
        log.info(">>>>>>>>>>>>>>>>测试EventListener.testA:", event);
        log.info("处理复杂业务中....");
    


控制层:ApplicationContext 中的publishEvent()会触发监听机制。

@RestController
@RequestMapping("/test")
public class testController 

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("/lister")
    public void getObjectProperties(@RequestParam String msg) 
        applicationContext.publishEvent(new MyApplicationEvent("测试", msg));
    


打印台

ApplicationListener 相对于@EventListener来说粒度更粗。

@Slf4j
@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> 
    @Override
    public void onApplicationEvent(MyApplicationEvent event) 
        log.info(">>>>>>>>>>>>>>>>测试ApplicationListener:", event);
    

												————  What is worth doing is worth doing well.

以上是关于Spring boot的监听这么简单?的主要内容,如果未能解决你的问题,请参考以下文章

Spring boot的监听这么简单?

Spring boot的监听这么简单?

spring boot 学习 ---- 使用事件监听

Spring boot集成Websocket,前端监听心跳实现

最棒 Spring Boot 干货总结(超详细,建议收藏)

最新Spring Boot干货总结(超详细,建议收藏)