观察者模式Spring之publishEvent事件处理

一、使用场景

这个一般什么时候使用,我们一般是在不同的bean直接进行信息传递,比如我们beanA的事件处理完后,需要beanB进行处理一些业务逻辑的时候这种情况就一般可以使用publish-event解决。

二、原理

ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicationListener接口来提供的,通过ApplicationContext的publishEvent()方法发布到ApplicationListener;。

一个事件模型有三个组成部分:被监听对象source(也称为事件源),事件event和监听对象listener。事件发布者在发布事件的时候->通知事件的监听者。

首先,由监听对象注册监听回调函数(Callback),当事件源触发了事件后,监听对象会收到事件源的信息,然后决定如何对事件源进行处理,简要流程如下图所示。
在这里插入图片描述

三、事件触发 && 监听处理过程

(1) 使用 org.springframework.context 包下的 ApplicationContext.publishEvent(ApplicationEvent appEvent) 发布事件
(2) 使用 org.springframework.context.event 包下的 @EventListener(事件名) 监听事件并处理。

注意:
(1) ApplicationContext.publishEvent 默认是同步操作, 并非发布后不管的异步操作,发布事件后需要等 @EventListener 执行完。
(2) 如果需要开启异步操作需要在@EventListener上增加@Async 注解。

四、代码实现

(1)CustomEvent

/**
 * 用户事件监听
 *
 * @author zhang
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomEvent {
    private String message;
}

(2)CustomEventListener

/**
 * @author zhang
 */
@Component
public class CustomEventListener {

    @EventListener(CustomEvent.class)
    public void onApplicationEvent(CustomEvent customEvent) throws InterruptedException {
        System.out.println("监听器接受消息:"+ customEvent.getMessage());
    }
}

(3)CustomController

/**
 * @author zhang
 */
@RestController
public class CustomController {

    @Resource
    private ApplicationContext applicationContext;

    @RequestMapping("/helloListener")
    public String helloListener(){
        System.out.println("模拟执行某业务逻辑A!");
        System.out.println("=======AAA================");
        System.out.println("模拟执行某业务逻辑B-> 即A执行完成后执行业务逻辑B");
        System.out.println("事件开始发布消息!");
        applicationContext.publishEvent(new CustomEvent("你好啊"));
        System.out.println("=======BBB================");
        System.out.println("模拟执行某业务逻辑B执行完毕!");
        return "success";
    }
}

五、执行结果

在这里插入图片描述
在这里插入图片描述

六、源码下载

点我下载源码
在这里插入图片描述

参考文章
https://www.bianchengquan.com/article/568343.html
https://blog.youkuaiyun.com/sxlzs_/article/details/122497880
https://blog.youkuaiyun.com/wufagang/article/details/112759722
https://zhuanlan.zhihu.com/p/403365107

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值