180609-Spring之事件驱动机制的简单使用

简介: 关于事件的发起与相应,在客户端的交互中可算是非常频繁的事情了,关于事件的发布订阅,在Java生态中,EventBus可谓是非常有名了,而Spring也提供了事件机制,本文则主要介绍后端如何在Spring的环境中,使用事件机制

image.png

文章链接:liuyueyi.github.io/hexblog/hex…


Spring之事件驱动机制的简单使用



关于事件的发起与相应,在客户端的交互中可算是非常频繁的事情了,关于事件的发布订阅,在Java生态中,EventBus可谓是非常有名了,而Spring也提供了事件机制,本文则主要介绍后端如何在Spring的环境中,使用事件机制


I. 使用姿势



主要借助

org.springframework.context.ApplicationEventPublisher#publishEvent(org.springframework.context.ApplicationEvent) 来发布事件,而接受方,则直接在处理的方法上,添加 @@EventListener注解即可


1. 事件定义


发布一个事件,所以第一件事就是要定义一个事件,对Spring而言,要求自定义的事件继承自ApplicationEvent类, 一个简单的demo如下


public class NotifyEvent extends ApplicationEvent {
    @Getter
    private String msg;
    public NotifyEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
}
复制代码


2. 发布事件


发布时间则比较简单,直接拿到ApplicationContext实例,执行publish方法即可,如下面给出一个简单的发布类


@Component
public class NotifyPublisher implements ApplicationContextAware {
    private ApplicationContext apc;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.apc = applicationContext;
    }
    // 发布一个消息
    public void publishEvent(int status, String msg) {
        if (status == 0) {
            apc.publishEvent(new NotifyEvent(this, msg));
        } else {
            apc.publishEvent(new NewNotifyEvent(this, msg, ((int) System.currentTimeMillis() / 1000)));
        }
    }
}
复制代码


3. 事件监听器


在方法上添加注解即可,如下


@Component
public class NotifyQueueListener {
    @EventListener
    public void consumerA(NotifyEvent notifyEvent) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("A: " + Thread.currentThread().getName() + " | " + notifyEvent.getMsg());
    }
    @EventListener
    public void consumerB(NewNotifyEvent notifyEvent) {
        System.out.println("B: " + Thread.currentThread().getName() + " | " + notifyEvent.getMsg());
    }
    @EventListener
    public void consumerC(NotifyEvent notifyEvent) {
        System.out.println("C: " + Thread.currentThread().getName() + " | " + notifyEvent.getMsg());
    }
}
复制代码


II. 疑问及解答



1. 发布与监听器的关联


上面给出了使用的姿势,看起来并不复杂,也比较容易使用,但是一个问题需要在使用之前弄明白了,发布事件和监听器是怎么关联起来的呢?


  • 根据方法的参数类型执行


那么如果发布者,推送的是一个NotifyEvent类型的事件,那么接收者是怎样的呢?


  • 参数为NotifyEvent以及其子类的监听器,都可以接收到消息


测试用例如下:


NewNotifyEvent 继承自上面的NotifyEvent

public class NewNotifyEvent extends NotifyEvent {
    @Getter
    private int version;
    public NewNotifyEvent(Object source, String msg) {
        super(source, msg);
    }
    public NewNotifyEvent(Object source, String msg, int version) {
        super(source, msg);
        this.version = version;
    }
}
复制代码


然后借助上面的消息发布者发送一个消息

@Test
public void testPublishEvent() throws InterruptedException {
    notifyPublisher.publishEvent(1, "新的发布事件! NewNotify");
    System.out.println("---------");
    notifyPublisher.publishEvent(0, "旧的发布事件! Notify");
}
复制代码


输出结果如下,对于NewNotifyEvent, 参数类型为NotifyEvent的consumerA, consumerC都可以接收到

A: main | 新的发布事件! NewNotify
C: main | 新的发布事件! NewNotify
B: main | 新的发布事件! NewNotify
---------
A: main | 旧的发布事件! Notify
C: main | 旧的发布事件! Notify
复制代码


2. 消息接收的顺序


上面消息处理是串行的,那么先后顺序怎么确定? (下面的答案不确定,有待深入源码验证!!!)


  • 先扫描到的bean先处理
  • 同一个bean中,按精确匹配,先后定义顺序进行


3. 异步消费


对于异步消费,即在消费者方法上添加一个@Async注解,并需要在配置文件中,开启


异步支持

@Async
@EventListener
public void processNewNotifyEvent(NewNotifyEvent newNotifyEvent) {
    System.out.println("new notifyevent: " + newNotifyEvent.getMsg() + " : " + newNotifyEvent.getVersion());
}
复制代码


配置支持

@Configuration
@EnableAsync
public class AysncListenerConfig implements AsyncConfigurer {
    /**
     * 获取异步线程池执行对象
     *
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolExecutor(5, 10, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(),
                new DefaultThreadFactory("test"), new ThreadPoolExecutor.CallerRunsPolicy());
    }
}



相关文章
|
1月前
|
存储 安全 Java
事件的力量:探索Spring框架中的事件处理机制
事件的力量:探索Spring框架中的事件处理机制
36 0
|
1月前
|
设计模式 前端开发 Java
【深入浅出Spring原理及实战】「夯实基础系列」360全方位渗透和探究SpringMVC的核心原理和运作机制(总体框架原理篇)
【深入浅出Spring原理及实战】「夯实基础系列」360全方位渗透和探究SpringMVC的核心原理和运作机制(总体框架原理篇)
45 0
|
1月前
|
Java 开发者 UED
Spring Boot的全局异常处理机制
【2月更文挑战第13天】
116 0
|
1月前
|
XML Java 数据格式
聊聊Spring事件及其应用
在 JDK 中已经提供相应的自定义事件发布功能的基础类: - `java.util.EventObject`类 :自定义**事件**类型 - `java.util.EventListener`接口:事件的**监听器**
47 1
聊聊Spring事件及其应用
|
1月前
|
人工智能 JSON 前端开发
【Spring boot实战】Springboot+对话ai模型整体框架+高并发线程机制处理优化+提示词工程效果展示(按照框架自己修改可对接市面上百分之99的模型)
【Spring boot实战】Springboot+对话ai模型整体框架+高并发线程机制处理优化+提示词工程效果展示(按照框架自己修改可对接市面上百分之99的模型)
|
1月前
|
XML Java 数据格式
编织Spring魔法:解读核心容器中的Beans机制【beans 一】
编织Spring魔法:解读核心容器中的Beans机制【beans 一】
62 0
|
1月前
|
Java 测试技术 开发者
Spring IoC容器通过依赖注入机制实现控制反转
【4月更文挑战第30天】Spring IoC容器通过依赖注入机制实现控制反转
32 0
|
7天前
|
Java 应用服务中间件 Spring
解析Spring Boot自动装配的原理与机制
解析Spring Boot自动装配的原理与机制
17 4
|
11天前
|
JSON 安全 Java
Spring Security 与 JWT、OAuth 2.0 整合详解:构建安全可靠的认证与授权机制
Spring Security 与 JWT、OAuth 2.0 整合详解:构建安全可靠的认证与授权机制
25 0
|
1月前
|
缓存 NoSQL Java
17:缓存机制-Java Spring
17:缓存机制-Java Spring
56 5