springboot自定义事件发布及监听

自定义线程池

java 复制代码
@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;
    }
}

实体类

java 复制代码
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层

java 复制代码
public interface StudentService {
	 void sendStudentEvent(String id, String name);
}

serviceImpl层

java 复制代码
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    ApplicationEventPublisher eventPublisher;
	
	@Override
    @Async("myExecutor")
	public void sendStudentEvent(String id, String name){
		StudentEvent studentEvent = new StudentEvent(this,id,name);
		eventPublisher.publishEvent(studentEvent);
	}
}

事件监听

java 复制代码
@Component
public class MyStudentEventListener {

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

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

java 复制代码
@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 注解:

java 复制代码
@Component
@ConditionalOnProperty(name = "myapp.event.listener.enabled", havingValue = "true")
public class MyEventListener {

    @EventListener
    public void handleEvent(MyEvent event) {
        // 处理事件
    }
}

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

相关推荐
用户409932250212几秒前
Vue3动态样式控制:ref、reactive、watch与computed的应用场景与区别是什么?
后端·ai编程·trae
心之语歌1 分钟前
3433.统计用户被提及情况
后端
爬山算法18 分钟前
Netty(17)Netty如何处理大量的并发连接?
java·后端
spencer_tseng30 分钟前
springcloud + javaframework + h5
java·spring·spring cloud
李慕婉学姐36 分钟前
Springboot面向电商的仓库管理系统05uc4267(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
pengkai火火火1 小时前
基于springmvc拓展机制的高性能日志审计框架的设计与实现
spring boot·安全·微服务·架构
月明长歌1 小时前
【码道初阶】【Leetcode606】二叉树转字符串:前序遍历 + 括号精简规则,一次递归搞定
java·数据结构·算法·leetcode·二叉树
原来是好奇心1 小时前
深入Spring Boot源码(八):高级特性与扩展点深度解析
java·源码·springboot
oioihoii1 小时前
C++共享内存小白入门指南
java·c++·算法