Spring Boot - Application Events 同步 VS 异步 发布订阅事件实战

news/2024/7/27 7:47:08/文章来源:https://blog.csdn.net/yangshangwei/article/details/135574826

文章目录

  • Pre
  • Code
  • 基础工程
    • 启动类
    • 切入口
    • 事件
  • 发布事件
  • 同步 Listener
  • 异步Listener
    • 增加@EnableAsync
    • 增加 @Async
  • 测试

在这里插入图片描述


Pre

Spring Boot - Application Events 的发布顺序_ApplicationStartingEvent

Spring Boot - Application Events 的发布顺序_ApplicationEnvironmentPreparedEvent

Spring Boot - Application Events 的发布顺序_ApplicationContextInitializedEvent

Spring Boot - Application Events 的发布顺序_ApplicationPreparedEvent

Spring Boot - Application Events 的发布顺序_ContextRefreshedListener

Spring Boot - Application Events 的发布顺序_ApplicationStartedEvent

Spring Boot - Application Events 的发布顺序_AvailabilityChangeEvent

Spring Boot - Application Events 的发布顺序_ApplicationReadyEvent

Spring Boot - Application Events 的发布顺序_ApplicationFailedEvent

Spring Boot - ApplicationRunner && CommandLineRunner扩展接口


Code

在这里插入图片描述


基础工程

启动类

@SpringBootApplication 
public class LifeCycleApplication {/*** 除了手工add , 在 META-INF下面 的 spring.factories 里增加* org.springframework.context.ApplicationListener=自定义的listener 也可以** @param args*/public static void main(String[] args) {SpringApplication.run(LifeCycleApplication.class, args);}
}

META-INF中增加 spring.factories文件

org.springframework.context.ApplicationListener=\
com.artisan.practise.listeners.SpringBuiltInEventsListener

切入口

package com.artisan.practise.listeners;import com.artisan.practise.publish.Publisher;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.SpringApplicationEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
public class SpringBuiltInEventsListener implements ApplicationListener<SpringApplicationEvent>, ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}@Overridepublic void onApplicationEvent(SpringApplicationEvent event) {System.out.println("SpringApplicationEvent Received - " + event);// Initializing publisher for custom eventthis.initPublisher(event);}private void initPublisher(SpringApplicationEvent event) {if (event instanceof ApplicationReadyEvent) {this.applicationContext.getBean(Publisher.class).publishEvent();}}
}

事件

package com.artisan.practise.events;import org.springframework.context.ApplicationEvent;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
public class UserCreatedEvent extends ApplicationEvent {private static final long serialVersionUID = 1L;private String name;public UserCreatedEvent(Object source, String name) {super(source);this.name = name;}public String getName() {return this.name;}}
package com.artisan.practise.events;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
public class UserRemovedEvent {public String name;public UserRemovedEvent(String name) {this.name = name;}public String getName() {return this.name;}}


发布事件

package com.artisan.practise.publish;import com.artisan.practise.events.UserCreatedEvent;
import com.artisan.practise.events.UserRemovedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
@Component
public class Publisher {@Autowiredprivate ApplicationEventPublisher publisher;public void publishEvent() {System.out.println("========================"  + Thread.currentThread().getName());// Async Eventpublisher.publishEvent("I'm Async");// @EventListener Annotated and ApplicationListenerpublisher.publishEvent(new UserCreatedEvent(this, "Artisan"));publisher.publishEvent(new UserRemovedEvent("Artisan"));// Conditional Listenerpublisher.publishEvent(new UserCreatedEvent(this, "reflectoring"));publisher.publishEvent(new UserRemovedEvent("reflectoring"));}}

同步 Listener

package com.artisan.practise.listeners;import com.artisan.practise.events.UserCreatedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
@Component
class UserCreatedListener implements ApplicationListener<UserCreatedEvent> {@Overridepublic void onApplicationEvent(UserCreatedEvent event) {System.out.println(String.format("%s - User created: %s",Thread.currentThread().getName() , event.getName()));}
}
package com.artisan.practise.listeners;import com.artisan.practise.events.UserRemovedEvent;
import com.artisan.practise.response.ReturnedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
@Component
public class UserRemovedListener {@EventListenerReturnedEvent handleUserRemovedEvent(UserRemovedEvent event) {System.out.println(String.format("%s - User removed (@EventListerner): %s", Thread.currentThread().getName(), event.getName()));// Spring will send ReturnedEvent as a new eventreturn new ReturnedEvent();}// Listener to receive the event returned by Spring@EventListenervoid handleReturnedEvent(ReturnedEvent event) {System.out.println(String.format("%s - ReturnedEvent received.", Thread.currentThread().getName()));}@EventListener(condition = "#event.name eq 'reflectoring'")void handleConditionalListener(UserRemovedEvent event) {System.out.println(String.format("%s - User removed (Conditional): %s", Thread.currentThread().getName(), event.getName()));}@TransactionalEventListener(condition = "#event.name eq 'reflectoring'", phase = TransactionPhase.AFTER_COMPLETION)void handleAfterUserRemoved(UserRemovedEvent event) {System.out.println(String.format("%s - User removed (@TransactionalEventListener): %s", Thread.currentThread().getName(), event.getName()));}}

异步Listener

增加@EnableAsync

启动类增加@EnableAsync

@SpringBootApplication
@EnableAsync
public class LifeCycleApplication {}

@EnableAsync 是一个在 Spring 框架中使用的注解,它用于启用 Spring 的异步执行功能。当在一个配置类上加上 @EnableAsync 注解时,Spring 容器会设置异步任务执行的支持。这允许你将任务标记为异步,并且可以在不同的线程中执行它们,从而提高应用程序的响应能力和吞吐量。
以下是一些关键点,用以解释 @EnableAsync 注解的功能和用法:

  1. 异步执行: 在 Spring 应用中,你可以使用 @Async 注解来标记一个方法为异步执行。当方法被调用时,它将在一个单独的线程中运行,而不是在调用线程中立即执行。

  2. 启用异步执行: 为了使 @Async 注解生效,必须在 Spring 应用程序的配置中启用异步支持。这通常是通过在 Spring 配置类上添加 @EnableAsync 注解来实现的。

  3. 线程池: @EnableAsync 注解允许你定义一个自定义的线程池,Spring 会使用这个线程池来执行异步任务。如果你没有提供线程池,Spring 会使用默认的线程池。

  4. 异常处理: 异步方法执行中发生的异常通常不会传递给调用者。@EnableAsync 支持异常处理配置,允许你定义如何处理这些异常。

  5. 调度器: 你可以指定一个 TaskScheduler Bean,Spring 使用它来调度异步任务。默认情况下,Spring 容器会创建一个 SimpleAsyncTaskExecutor 实例。

  6. 顺序执行: 如果你需要确保某些异步方法按照严格的顺序执行,可以使用 @Async 注解的 dependsOn 属性来指定依赖关系。

使用 @EnableAsync 注解可以让开发者轻松地构建高并发的应用程序,提高应用程序处理大量并发请求的能力,同时保持代码的清晰和易管理性。在微服务架构和分布式系统中,异步通信是提高系统解耦和性能的关键技术之一。


增加 @Async

增加 @Async

package com.artisan.practise.listeners;import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;@Component
class AsyncListener {@Async@EventListenervoid handleAsyncEvent(String event) {System.out.println(String.format("%s - Async event recevied: %s  ",  Thread.currentThread().getName(), event));}}

@Async 是一个方法级别的注解,在 Spring 框架中用于标识一个方法应该以异步方式执行。当一个方法被标记为 @Async 时,它将在一个单独的线程中运行,而不是在调用它的线程中立即执行。这种方式可以避免阻塞调用线程,从而提高应用程序的响应能力和吞吐量。
以下是一些关于 @Async 注解的关键点:

  1. 异步方法执行: @Async 注解允许你将方法的执行放到一个单独的线程中,这样主线程就可以立即返回,继续处理其他任务。
  2. 线程池: @Async 注解通常与 @EnableAsync 注解一起使用,后者启用了异步支持并定义了一个线程池。异步方法通常会在这个线程池中分配线程来执行。
  3. 异常处理: 异步方法执行过程中出现的异常通常不会传递给调用者。但是,可以通过配置 AsyncUncaughtExceptionHandler 来处理这些异常。
  4. 调度器: @Async 注解可以指定一个 TaskScheduler Bean,它负责调度异步任务的执行。如果没有指定,Spring 会默认使用一个 SimpleAsyncTaskExecutor
  5. 顺序执行: 如果需要确保某些异步方法按照严格的顺序执行,可以使用 @Async 注解的 dependsOn 属性来指定依赖关系。
  6. 触发器: @Async 方法可以由其他 @Async 方法触发,这允许创建异步的工作流和回调。
  7. 注解兼容性: @Async 注解可以与 @Transactional 注解一起使用,但是需要确保事务性注解和异步注解在方法上的使用是兼容的。

异步编程 - 08 Spring框架中的异步执行_TaskExecutor接口和@Async应用篇

异步编程 - 09 Spring框架中的异步执行_@Async注解异步执行原理&源码解析


测试

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_925436.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

IntelliJ IDEA - 快速去除 mapper.xml 告警线和背景(三步走)

1、去掉 No data sources configure 警告 Settings&#xff08;Ctrl Alt S&#xff09; ⇒ Editor ⇒ Inspections ⇒ SQL ⇒ No data sources configure 2、去掉 SQL dialect is not configured 警告 Settings&#xff08;Ctrl Alt S&#xff09; ⇒ Editor ⇒ Inspecti…

GPT应用开发:运行你的第一个聊天程序

本系列文章介绍基于OpenAI GPT API开发应用的方法&#xff0c;适合从零开始&#xff0c;也适合查缺补漏。 本文首先介绍基于聊天API编程的方法。 环境搭建 很多机器学习框架和类库都是使用Python编写的&#xff0c;OpenAI提供的很多例子也是Python编写的&#xff0c;所以为了…

如何利用小程序介绍公司品牌形象?

企业小程序的建设对于现代企业来说已经成为了一项必不可少的工作。随着移动互联网的快速发展&#xff0c;越来越多的职场人士和创业老板希望通过小程序来提升企业形象&#xff0c;增强与用户的互动&#xff0c;实现更好的商业效果。在这个过程中&#xff0c;使用第三方制作平台…

数据结构排序算法总结

直接插入排序 折半插入排序 希尔排序 冒泡排序 快速排序 选择排序 堆排序 归并排序 1.直接插入排序 前面的有序 后面的无序&#xff0c;无序元素插入到前面的有序列表中 int len nums.length, i 1, j 0;for(i1; i<len; i){int ele nums[i];// 插入过程for(j i…

【上分日记】第379场周赛(分类讨论 + 数学 + 前缀和)

文章目录 前言正文1.3000. 对角线最长的矩形的面积2.3001. 捕获黑皇后需要的最少移动次数3.3002. 移除后集合的最多元素数3.3003. 执行操作后的最大分割数量 总结尾序 前言 终于考完试了&#xff0c;考了四天&#xff0c;也耽搁了四天&#xff0c;这就赶紧来补这场周赛的题了&a…

gitee完整使用教程,创建项目并上传

目录 一 什么是gitee 二 安装Git 三 登录gitee&#xff0c;生成密钥 四 配置SSH密钥 五 创建项目 六 克隆仓库到本地 七 关联本地工程到远程仓库 八 添加文件 九 异常处理 十 删除仓储 十一 git常用命令 一 什么是gitee gitee是开源中国推出的基于git的代码托管服务…

3种ffmpeg-web端视频直播推流方案

ffmpeg-web端视频直播推流方案 记录了三种 ffmpeg 工具进行推流的方法&#xff0c;并在web端实现直播效果。 一. node-media-server ffmpeg 推流rtmp 安装node-media-server依赖,新建app.js运行 npm install node-media-server -g const NodeMediaServer require(node-…

e2studio开发三轴加速度计LIS2DW12(4)----测量倾斜度

e2studio开发三轴加速度计LIS2DW12.4--测量倾斜度 概述视频教学样品申请源码下载计算倾斜角度工作原理单轴倾斜检测双轴倾斜检测三轴倾斜检测通信模式管脚定义IIC通信模式速率新建工程工程模板保存工程路径芯片配置工程模板选择时钟设置UART配置UART属性配置设置e2studio堆栈e…

004 Golang-channel-practice 左右括号匹配

第四题 左右括号打印 一个协程负责打印“&#xff08;”&#xff0c;一个协程负责打印“&#xff09;”&#xff0c;左右括号的数量要匹配。在这道题目里&#xff0c;我在main函数里进行了一个死循环。会产生一个随机数&#xff0c;随机数就是接下来要打印的左括号的数量。 例…

spring boot mybatis plus mapper如何自动注册到spring bean容器

##Import(AutoConfiguredMapperScannerRegistrar.class) ##注册MapperScannerConfigurer ##MapperScannerConfigurer.postProcessBeanDefinitionRegistry方法扫描注册mapper ##找到mapper候选者 ##过滤mapper 类 候选者 ##BeanDefinitionHolder注册到spring 容器

竞赛保研 基于深度学习的动物识别 - 卷积神经网络 机器视觉 图像识别

文章目录 0 前言1 背景2 算法原理2.1 动物识别方法概况2.2 常用的网络模型2.2.1 B-CNN2.2.2 SSD 3 SSD动物目标检测流程4 实现效果5 部分相关代码5.1 数据预处理5.2 构建卷积神经网络5.3 tensorflow计算图可视化5.4 网络模型训练5.5 对猫狗图像进行2分类 6 最后 0 前言 &#…

c++泛型算法相关笔记

一. 泛型算法 1. 前言 泛型算法&#xff1a;可以支持多种类型的算法 此处主要来讨论怎么使用标准库中定义的泛型算法<algorithm>, numeric, ranges. 在引入泛型算法之前&#xff0c;还有一种是方法的形式&#xff0c;比如说std::sort 和std::list::sort&#xff0c;前者…

微信小程序上传并显示图片

实现效果&#xff1a; 上传前显示&#xff1a; 点击后可上传&#xff0c;上传后显示&#xff1a; 源代码&#xff1a; .wxml <view class"{{company_logo_src?blank-area:}}" style"position:absolute;top:30rpx;right:30rpx;height:100rpx;width:100rp…

力扣67. 二进制求和算法

一、【写在前面】 这道题需要&#xff0c;给你两个字符串比如 a "1010", b "1011"答案是&#xff1a;"10101" 然后需要你给出计算结果&#xff0c;那么我们很容易想到两种做法 1. 调库做法&#xff1a;直接转化为整数&#xff0c;然后用内…

在CentOS上设置和管理静态HTTP网站的版本控制

在CentOS上设置和管理静态HTTP网站的版本控制是一项重要的任务&#xff0c;它可以帮助您跟踪和回滚对网站所做的更改&#xff0c;确保数据的一致性和完整性。以下是在CentOS上设置和管理静态HTTP网站的版本控制的步骤&#xff1a; 安装版本控制系统在CentOS上安装Git或其他版本…

K8S--Ingress的作用

原文网址&#xff1a;K8S--Ingress的作用-CSDN博客 简介 本文介绍K8S的Ingress的作用。 ----------------------------------------------------------------------------------------------- 分享Java真实高频面试题&#xff0c;吊打面试官&#xff1a; Java后端真实面试题…

[后端] 微服务的前世今生

微服务的前世今生 整体脉络: 单体 -> 垂直划分 -> SOA -> micro service 微服务 -> services mesh服务网格 -> future 文章目录 微服务的前世今生单一应用架构特征优点&#xff1a;缺点&#xff1a; 垂直应用架构特征优点缺点 SOA 面向服务架构特征优点缺点 微服…

STM32快速复制MX25L1606E系列Flash

去年做了一个使用RS485对PIC18F45K80系列单片机进行在线升级的程序&#xff0c;如果是小批量的出厂烧录程序和升级验证&#xff08;出厂前肯定要测试单片机是否能正常读写Flash&#xff09;是可以的&#xff0c;但是后来产品订单量很大&#xff0c;生产线的烧录及升级验证就很缓…

Android Retrofit使用详情

一、 Retrofit是什么 Retrofit是Android用来接口请求的网络框架&#xff0c;内部是基于OkHttp实现的&#xff0c;retrofit负责接口请求的封装&#xff0c;retrofit可以直接将接口数据解析为Bean类、List集合等&#xff0c;直接简化了中间繁琐的数据解析过程 二、 Retrofit的简单…

使用 Apache POI 更新/覆盖 特定的单元格

使用 Apache POI 更新特定的单元格 一. 需求二. 实现三. 效果 一. 需求 将以下表中第4行&#xff0c;第4列的单元格由“张宇”更新为“汤家凤”&#xff0c;并将更行后的结果写入新的Excel文件中&#xff1b; 二. 实现 使用Apache POI&#xff0c;可以精确定位到需要更改的单…