Springboot中的事件Event
事件Event作为一种常用的线程通讯工具,在Springboot中可以方便地提供开发者进行线程交互。
1.事件定义
1 import org.springframework.context.ApplicationEvent;
2
3 /**
4 * WebSocket触发事件定义
5 * @author : Asp1rant
6 * @date : 19-3-11 上午10:33
7 */
8
9 public class WebsocketMessageEvent extends ApplicationEvent {
10
11 public String username;
12 public String message;
13
14 public WebsocketMessageEvent(Object source, String username, String message){
15 super(source);
16 this.username = username;
17 this.message = message;
18 }
19 }
2.编写服务,编写时添加接口供外部调用发布
1 import com.baosight.tos.util.event.WebsocketMessageEvent;
2 import org.springframework.beans.factory.annotation.Autowired;
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.stereotype.Service;
5
6 /**
7 * Websocket事件服务
8 * @author : Asp1rant
9 * @date : 19-3-11 上午10:36
10 */
11
12 @Service
13 public class WebsocketMessageService {
14
15 @Autowired
16 ApplicationContext applicationContext;
17
18 public void pubWebsocketMessage(String username, String message){
19 applicationContext.publishEvent(new WebsocketMessageEvent(this, username, message));
20 }
21
22 }
3.事件监听,两种写法:
3.1 定义监听器
1 import org.springframework.context.ApplicationListener;
2
3 public class WebsocketEventListener implements ApplicationListener<WebsocketMessageEvent> {
4
5 @Override
6 public void onApplicationEvent(WebsocketMessageEvent websocketMessageEvent){
7 System.out.println("监听到WebsocketMessageEvent事件");
8 try {
9 Thread.sleep(2000);
10 } catch (InterruptedException e) {
11 e.printStackTrace();
12 }
13 }
14
15 }
3.2 注解EventListener
1 @EventListener
2 public synchronized void WebsocketListener(WebsocketMessageEvent event){
3 System.out.println("监听到WebsocketMessageEvent事件");
4 }
5 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具