Spring事件驱动模型,简单来说类似于Message-Queue消息队列中的Pub/Sub发布/订阅模式,也类似于Java设计模式中的观察者模式。

自定义事件

Spring的事件接口位于org.springframework.context.ApplicationEvent,源码如下:

public abstract class ApplicationEvent extends EventObject {
private static final long serialVersionUID = 7099057708183571937L;
private final long timestamp;
public ApplicationEvent(Object source) {
super(source);
this.timestamp = System.currentTimeMillis();
}
public final long getTimestamp() {
return this.timestamp;
}
}

继承了Java的事件对象EventObject,所以可以使用getSource()方法来获取到事件传播对象。

自定义Spring事件

public class CustomSpringEvent extends ApplicationEvent {
private String message; public CustomSpringEvent(Object source, String message) {
super(source);
this.message = message;
} public String getMessage() {
return message;
}
}

然后定义事件监听器,该监听器实际上等同于消费者,需要交给Spring容器管理。

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
@Override
public void onApplicationEvent(CustomSpringEvent event) {
System.out.println("Received spring custom event - " + event.getMessage());
}
}

最后定义事件发布者

@Component
public class CustomSpringEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher; public void doStuffAndPublishAnEvent(final String message) {
System.out.println("Publishing custom event. ");
CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
applicationEventPublisher.publishEvent(customSpringEvent);
}
}

创建测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomSpringEventPublisherTest { @Autowired
private CustomSpringEventPublisher publisher; @Test
public void publishStringEventTest() {
publisher.doStuffAndPublishAnEvent("111");
}
}

运行测试类,可以看到控制台打印了两条重要信息

//发布事件
Publishing custom event.
//监听器得到了事件,并相应处理
Received spring custom event - 111

由于Spring事件是发布/订阅的模式,而发布订阅模式有以下三种情况

  1. 1生产者 - 1消费者
  2. 1生产者 - 多消费者
  3. 多生产者 - 多消费者

上面举的例子是第一种情况,我们来试试其他两个情况

继续创建一个事件监听器作为消费者:

@Component
public class CustomSpringEventListener2 implements ApplicationListener<CustomSpringEvent> {
@Override
public void onApplicationEvent(CustomSpringEvent event) {
System.out.println("CustomSpringEventListener2 Received spring custom event - " + event.getMessage());
}
}

运行测试类后,可以观察到,控制台顺序打印了两条消费信息:

Publishing custom event.
CustomSpringEventListener1 Received spring custom event - 111
CustomSpringEventListener2 Received spring custom event - 111

说明,Spring的发布订阅模式是广播模式,所有消费者都能接受到消息,并正常消费

再试试第三种多生产者 - 多消费者的情况

继续创建一个发布者,

@Component
public class CustomSpringEventPublisher2 {
@Autowired
private ApplicationEventPublisher applicationEventPublisher; public void doStuffAndPublishAnEvent(final String message) {
System.out.println("CustomSpringEventPublisher2 Publishing custom event. ");
CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
applicationEventPublisher.publishEvent(customSpringEvent);
}
}

控制台输出:

CustomSpringEventPublisher Publishing custom event.
CustomSpringEventListener1 Received spring custom event - 111
CustomSpringEventListener2 Received spring custom event - 111
CustomSpringEventPublisher2 Publishing custom event.
CustomSpringEventListener1 Received spring custom event - 222
CustomSpringEventListener2 Received spring custom event - 222

从以上输出内容,我们可以猜测到,Spring的事件发布订阅机制是同步进行的,也就是说,事件必须被所有消费者消费完成之后,发布者的代码才能继续往下走,这显然不是我们想要的效果,那有没有异步执行的事件呢?

Spring中的异步事件

要使用Spring 的异步事件,我们需要自定义异步事件配置类

@Configuration
public class AsynchronousSpringEventsConfig {
@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
SimpleApplicationEventMulticaster eventMulticaster
= new SimpleApplicationEventMulticaster(); eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
return eventMulticaster;
}
}

发布和订阅的代码不用变动,直接运行测试类,控制台将打印出:

CustomSpringEventPublisher Publishing custom event.
CustomSpringEventPublisher2 Publishing custom event.
CustomSpringEventListener1 Received spring custom event - 111
CustomSpringEventListener2 Received spring custom event - 111
CustomSpringEventListener2 Received spring custom event - 222
CustomSpringEventListener1 Received spring custom event - 222

可以看到,两个发布者几乎同时运行,证明监听器是异步执行的,没有阻塞住发布者的代码。准确的说,监听器将在一个单独的线程中异步处理事件。

Spring自带的事件类型

事件驱动在Spring中是被广泛采用的,我们查看ApplicationEvent的子类可以发现许多Event事件,在此不赘述。

注解驱动的监听器

从Spring 4.2开始,事件监听器不需要是实现ApplicationListener接口的bean,它可以通过@EventListener注解在任何被Spring容器管理的bean的公共方法上。

@Component
public class AnnotationDrivenContextStartedListener {
@EventListener
public void handleContextStart(CustomSpringEvent cse) {
System.out.println("Handling Custom Spring Event.");
}
}

控制台输出结果:

CustomSpringEventPublisher Publishing custom event.
Handling Custom Spring Event.
CustomSpringEventPublisher2 Publishing custom event.
Handling Custom Spring Event.

同样的,我们可以看出,这个事件监听器是同步执行的,如果要改为异步监听器,在事件方法上加上@Async,并且在Spring应用中开启异步支持(在SpringBootApplication上添加@EnableAsync)。

@Component
public class AnnotationDrivenContextStartedListener {
@Async
@EventListener
public void handleContextStart(CustomSpringEvent cse) {
System.out.println("Handling Custom Spring Event.");
}
}

再次运行测试类:

CustomSpringEventPublisher Publishing custom event.
CustomSpringEventPublisher2 Publishing custom event.
Handling Custom Spring Event.
Handling Custom Spring Event.

泛型支持

创建一个通用泛型事件模型

@Data
public class GenericSpringEvent<T> {
private T message;
protected boolean success; public GenericSpringEvent(T what, boolean success) {
this.message = what;
this.success = success;
}
}

注意GenericSpringEventCustomSpringEvent之间的区别。我们现在可以灵活地发布任何任意事件,并且不再需要从ApplicationEvent扩展。

这样的话,我们无法像之前一样,通过继承ApplicationListener的方式来定义一个监听器,因为ApplicationListener定义了事件必须是ApplicationEvent的子类。所以,我们只能使用注解驱动的监听器。

通过在@EventListener注释上定义布尔SpEL表达式,也可以使事件监听器成为条件。在这种情况下,只会为成功的String的GenericSpringEvent调用事件处理程序:

@Component
public class AnnotationDrivenEventListener {
@EventListener(condition = "#event.success")
public void handleSuccessful(GenericSpringEvent<String> event) {
System.out.println("Handling generic event (conditional).");
}
}

定义具体类型的事件:

public class StringGenericSpringEvent extends GenericSpringEvent<String> {
public StringGenericSpringEvent(String message, boolean success) {
super(message, success);
}
}

定义发布者:

@Component
public class StringGenericSpringEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher; public void doStuffAndPublishAnEvent(final String message, final boolean success) {
System.out.println("CustomSpringEventPublisher Publishing custom event. ");
StringGenericSpringEvent springEvent = new StringGenericSpringEvent(message, success);
applicationEventPublisher.publishEvent(springEvent);
}
}

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomSpringEventPublisherTest { @Autowired
private StringGenericSpringEventPublisher publisher; @Test
public void publishStringEventTest() {
publisher.doStuffAndPublishAnEvent("success", true);
publisher.doStuffAndPublishAnEvent("failed", false);
}
}

运行结果:

CustomSpringEventPublisher Publishing custom event.
Handling generic event (conditional) success
CustomSpringEventPublisher Publishing custom event.

监听器只处理了成功的事件,成功忽略掉了失败的事件。这样的好处是,可以为同一个事件定义成功和失败不同的操作。

Spring事件的事务绑定

从Spring 4.2开始,框架提供了一个新的@TransactionalEventListener注解,它是@EventListener的扩展,允许将事件的侦听器绑定到事务的一个阶段。绑定可以进行以下事务阶段:

  • AFTER_COMMIT(默认的):在事务成功后触发
  • AFTER_ROLLBACK:事务回滚时触发
  • AFTER_COMPLETION:事务完成后触发,不论是否成功
  • BEFORE_COMMIT:事务提交之前触发

总结

  1. Spring中处理事件的基础知识:创建一个简单的自定义事件,发布它,然后在监听器中处理它。
  2. 在配置中启用事件的异步处理。
  3. Spring 4.2中引入的改进,例如注释驱动的侦听器,更好的泛型支持以及绑定到事务阶段的事件。

Spring Event事件驱动的更多相关文章

  1. EventBus VS Spring Event

    EventBus VS Spring Event 本地异步处理,采用事件机制 可以使 代码解耦,更易读.事件机制实现模式是 观察者模式(或发布订阅模式),主要分为三部分:发布者.监听者.事件. Gua ...

  2. spring event

    昨天看到了一遍关于spring event的帖子,觉得很好,就照着敲了一份代码,感觉对spring event有了进一步的认识.帖子链接:https://segmentfault.com/a/1190 ...

  3. 自定义Spring event

    通过Spring自定义event 首先我们定义我们的event类 package com.hyenas.spring.custom.event; import org.springframework. ...

  4. nginx源代码分析--event事件驱动初始化

    1.在nginx.c中设置每一个核心模块的index ngx_max_module = 0; for (i = 0; ngx_modules[i]; i++) { ngx_modules[i]-> ...

  5. spring的事件驱动模型

    在工作中会遇到这样的业务,生成一个订单后需要给指定的用户发送短信或者邮件,但是短信或者邮件发送失败又不会影响正常的业务: 这里介绍通过ApplicationContext和spring的@EventL ...

  6. 配置Apache运行在event事件驱动模式下

    (1)启用MPM Include conf/extra/httpd-mpm.conf (2)配置evnet MPM参数  <IfModule event.c> #default 3 Ser ...

  7. spring事件驱动模型--观察者模式在spring中的应用

    spring中的事件驱动模型也叫作发布订阅模式,是观察者模式的一个典型的应用,关于观察者模式在之前的博文中总结过,http://www.cnblogs.com/fingerboy/p/5468994. ...

  8. spring中自定义Event事件的使用和浅析

    在我目前接触的项目中,用到了许多spring相关的技术,框架层面的spring.spring mvc就不说了,细节上的功能也用了不少,如schedule定时任务.Filter过滤器. intercep ...

  9. 从spring框架中的事件驱动模型出发,优化实际应用开发代码

    一.事件起源 相信很多人在使用spring框架进行开发时,都会遇到这样的需求:在spring启动后,立即加载部分资源(例如:spring启动后立刻加载资源初始化到redis中).当我去解决这个问题时发 ...

随机推荐

  1. ARTS Week 11

    Jan 6, 2020 ~ Jan 12, 2020 Algorithm Problem 108 Convert Sorted Array to Binary Search Tree (将有序数组转化 ...

  2. Spring Boot 2.x基础教程:使用Spring Data JPA访问MySQL

    在数据访问这章的第一篇文章<Spring中使用JdbcTemplate访问数据库> 中,我们已经介绍了如何使用Spring Boot中最基本的jdbc模块来实现关系型数据库的数据读写操作. ...

  3. win10系统下安装JDK1.8及配置环境变量的方法

    本次演示基于windows10操作系统,如果你是linux,请参考:https://www.yn2333.com/archives/linux上安装JDK8 1:下载安装包 地址:https://ww ...

  4. CAS 分析

    CAS是什么 (1) CAS(Compare and Swap) 比较并交换, 比较并交换是在多线程并发时用到的一种技术 (2) CAS是原子操作, 保证并发安全性, 而不是保证并发同步. (3) C ...

  5. python学习(4)循环语句

    循环语句主要有两个,一个是 while :一个是for in range() 以案例来说明: 写一个猜数字的游戏,正确的数字等于38.如果数字等于38,则提示正确,然后结束:如果数字大于38则提示大了 ...

  6. golang的timer一些坑

    本文代码部分基于dive-to-gosync-workshop的代码 Golang 的NewTimer方法调用后,生成的timer会放入最小堆,一个后台goroutine会扫描这个堆,将到时的time ...

  7. EF core (code first) 通过自定义 Migration History 实现多租户使用同一数据库时更新数据库结构

    前言 写这篇文章的原因,其实由于我写EF core 实现多租户的时候,遇到的问题. 具体文章的链接: Asp.net core下利用EF core实现从数据实现多租户(1) Asp.net core下 ...

  8. 使用jQuery的插件jquery.corner.js来实现圆角效果-详解

    jquery.corner.js可以实现各种块级元素的角效果,以下为演示,详见jquery_corner.html中的注释部分,并附百度盘下载 jquery_corner.html代码如下: < ...

  9. hadoop简介和环境

            Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速运算和存储. Hadoop实现了一个 ...

  10. Vscode使用

    一. Vscode使用 1. 点击最下方的错误警告显示条,出现四个选项最后一个为终端命令(dos命令) 2. 提交代码输入提交信息,打勾提交,选择类似刷新按钮进行推送 3. 同步代码点击类似刷新按钮即 ...