当前位置: 首页 > news >正文

springboot自定义事件发布及监听

自定义线程池

@Configuration
public class MyThreadPool {//ThreadPoolTaskExecutor不会自动创建ThreadPoolExecutor,需要手动调initialize才会创建。如果@Bean就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize@Bean("myExecutor")public Executor createJobExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 线程池活跃的线程数executor.setCorePoolSize(20);// 设置线程队列最大线程数executor.setMaxPoolSize(40);// 设置等待队列大小executor.setQueueCapacity(200);// 线程池维护线程所允许的空闲时间executor.setKeepAliveSeconds(60);// 线程前缀名称executor.setThreadNamePrefix("myExecutor---: ");executor.initialize();return executor;}
}

实体类

public class StudentEvent extends ApplicationEvent{private String id;private String name;public StudentEvent(Object source, String id,String name) {super(source);this.id = id;this.name = name;}
}

事件发布

sevice层


public interface StudentService {void sendStudentEvent(String id, String name);
}

serviceImpl层

@Service
public class StudentServiceImpl implements StudentService {@AutowiredApplicationEventPublisher eventPublisher;@Override@Async("myExecutor")public void sendStudentEvent(String id, String name){StudentEvent studentEvent = new StudentEvent(this,id,name);eventPublisher.publishEvent(studentEvent);}
}

事件监听

@Component
public class MyStudentEventListener {@EventListener@Async("myExecutor")public void handleStudentEvent(StudentEvent studentEvent) {// 处理事件}
}

监听器的执行顺序
如果应用程序中有多个事件监听器,可以通过@Order 注解,指定它们的执行顺序。例如:

@Component
public class MyEventListener1 {@EventListener@Order(1)public void handleEvent(MyEvent event) {// 处理事件}
}@Component
public class MyEventListener2 {@EventListener@Order(2)public void handleEvent(MyEvent event) {// 处理事件}
}

监听器的条件
只想在特定条件下才执行事件监听器,可以使用 @ConditionalOnProperty 注解:

@Component
@ConditionalOnProperty(name = "myapp.event.listener.enabled", havingValue = "true")
public class MyEventListener {@EventListenerpublic void handleEvent(MyEvent event) {// 处理事件}
}

参考博客:https://blog.csdn.net/albert_xjf/article/details/131326148

http://www.lryc.cn/news/152722.html

相关文章:

  • 手写RPC框架--2.介绍Zookeeper
  • Docker harbor 私有仓库的部署和管理
  • 从零开始搭建AI网站(6):如何使用响应式编程
  • MPI之虚拟进程拓扑
  • Three.js相机参数及Z-Fighting问题的解决方案
  • 微信小程序食疗微信小程序的设计与实现
  • mac环境使用pkgbuild命令打pkg包的几个小细节
  • 在 Spring Boot 中集成 MinIO 对象存储
  • seq2seq与引入注意力机制的seq2seq
  • 【zookeeper】zookeeper介绍
  • 2023高教社杯数学建模思路 - 案例:ID3-决策树分类算法
  • springboot docker
  • docker-compose 部署nacos 整合 postgresql 为DB
  • 详解 ElasticSearch Kibana 配置部署
  • SourceTree 使用技巧
  • VIRTIO-BLK代码分析(0)概述
  • 【2023年11月第四版教材】第10章《进度管理》(第一部分)
  • 【多线程案例】生产者消费者模型(堵塞队列)
  • 数据结构与算法基础-学习-30-插入排序之直接插入排序、二分插入排序、希尔排序
  • Qt+C++桌面计算器源码
  • kubesphere安装Maven+JDK17 流水线打包
  • 百度搜索清理大量低质量网站
  • WPF数据模板
  • 浙江绿农环境:将废弃矿山变耕地,为生态文明贡献力量
  • HTML/CSS盒子模型
  • 《Java面向对象程序设计》学习笔记——CSV文件的读写与处理
  • opencv 案例05-基于二值图像分析(简单缺陷检测)
  • Elasticsearch入门介绍
  • QML Book 学习基础3(动画)
  • Lesson4-3:OpenCV图像特征提取与描述---SIFT/SURF算法