简介

说明

本文用示例介绍SpringBoot中的事件的用法及原理。

事件监听简述

事件的发布与监听从属于观察者模式;和MQ相比,事件的发布与监听偏向于处理服务内的某些逻辑。 

多个监听器可以监听同一个事件。例如:发布了事件A,监听器A和监听器B都监听了事件A,则监听器A和B都会进行处理。

同步与异步监听

监听方式 特点 使用时机
同步监听 发布器线程与监听器线程处于同一线程 1.监听逻辑处理较快
2.需要紧接着根据监听器追踪业务线程
异步监听 发布器线程与监听器线程处于不同线程 1.监听逻辑处理比较耗时
2.追求响应性能

事件的顺序

可使用实现Ordered接口的方式,调整监听器顺序。

注意:必须是同时实现 ApplicationListener<MyEvent>,Ordered这样的方法才能控制顺序。

下边几种都是无法控制顺序的:

  • @Component @EventListerner 实现Ordered
  • 实现 ApplicationListener<MyEvent> @Order

实例

同步监听(无序)

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

监听器

监听器1

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:        "   "MyListener");
        System.out.println("监听器所在线程:"   Thread.currentThread().getName());
        System.out.println("事件:          "   event);
        System.out.println("事件的数据:    "   event.getSource());
    }
}

监听器2

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 {
 
    @EventListener
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      "   "MyListener2");
        System.out.println("  所在线程:  "   Thread.currentThread().getName());
        System.out.println("  事件:      "   event);
        System.out.println("  事件的数据:"   event.getSource());
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:"   Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

可以发现,所有监听器和发布器都在同一个线程。 

同步监听(有序)

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

监听器

监听器1

package com.example.event;
 
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener implements ApplicationListener<MyEvent>,  Ordered {
    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      "   "MyListener");
        System.out.println("  所在线程:  "   Thread.currentThread().getName());
        System.out.println("  事件:      "   event);
        System.out.println("  事件的数据:"   event.getSource());
    }
 
    @Override
    public int getOrder() {
        return 2;
    }
}

监听器2

package com.example.event;
 
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 implements ApplicationListener<MyEvent>, Ordered {
 
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      "   "MyListener2");
        System.out.println("  所在线程:  "   Thread.currentThread().getName());
        System.out.println("  事件:      "   event);
        System.out.println("  事件的数据:"   event.getSource());
    }
 
    @Override
    public int getOrder() {
        return 1;
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:"   Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

如果将监听器的实现的Ordered顺序颠倒,则输出结果如下:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

异步监听(无序)

方法:

  • 开启异步监听
  • 在监听器上加@Async(此监听器必须是@Component方法注册的)

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

同步监听器

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:      "   "MyListener");
        System.out.println("  所在线程:  "   Thread.currentThread().getName());
        System.out.println("  事件:      "   event);
        System.out.println("  事件的数据:"   event.getSource());
    }
}

异步监听器

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
 
@Component
@Async
public class MyListener2 {
 
    @EventListener
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      "   "MyListener2");
        System.out.println("  所在线程:  "   Thread.currentThread().getName());
        System.out.println("  事件:      "   event);
        System.out.println("  事件的数据:"   event.getSource());
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:"   Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

启动类

package com.example;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
 
@SpringBootApplication
@EnableAsync
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  task-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

到此这篇关于详解SpringBoot实现同步与异步事件监听的文章就介绍到这了,更多相关SpringBoot事件监听内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

详解SpringBoot实现事件同步与异步监听的更多相关文章

  1. SpringBoot本地磁盘映射问题

    这篇文章主要介绍了SpringBoot本地磁盘映射问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  2. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  3. SpringBoot整合Javamail实现邮件发送的详细过程

    日常开发过程中,我们经常需要使用到邮件发送任务,比方说验证码的发送、日常信息的通知等,下面这篇文章主要给大家介绍了关于SpringBoot整合Javamail实现邮件发送的详细过程,需要的朋友可以参考下

  4. SpringBoot详细讲解视图整合引擎thymeleaf

    这篇文章主要分享了Spring Boot整合使用Thymeleaf,Thymeleaf是新一代的Java模板引擎,类似于Velocity、FreeMarker等传统引擎,关于其更多相关内容,需要的小伙伴可以参考一下

  5. java实现emqx设备上下线监听详解

    这篇文章主要为大家介绍了java实现emqx设备上下线监听详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  6. Springboot集成mybatis实现多数据源配置详解流程

    在日常开发中,若遇到多个数据源的需求,怎么办呢?通过springboot集成mybatis实现多数据源配置,简单尝试一下,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  7. JQuery在循环中绑定事件的问题详解

    下面小编就为大家带来一篇JQuery在循环中绑定事件的问题详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  8. 一篇文章带你了解vue.js的事件循环机制

    这篇文章主要为大家详细介绍了vue.js事件循环机制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

  9. SpringBoot使用Minio进行文件存储的实现

    本文主要介绍了SpringBoot使用Minio进行文件存储的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  10. 解析SpringBoot中使用LoadTimeWeaving技术实现AOP功能

    这篇文章主要介绍了SpringBoot中使用LoadTimeWeaving技术实现AOP功能,AOP面向切面编程,通过为目标类织入切面的方式,实现对目标类功能的增强,本文给大家介绍的非常详细,需要的朋友可以参考下

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部