事件Event作为一种常用的线程通讯工具,在Springboot中可以方便地提供开发者进行线程交互。

1.事件定义

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 Springboot中的事件Event 随笔 第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 }
Springboot中的事件Event 随笔 第2张

 

2.编写服务,编写时添加接口供外部调用发布

Springboot中的事件Event 随笔 第3张
 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 }
Springboot中的事件Event 随笔 第4张

3.事件监听,两种写法:

3.1 定义监听器

Springboot中的事件Event 随笔 第5张
 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 }
Springboot中的事件Event 随笔 第6张

3.2 注解EventListener

1  @EventListener 2 public synchronized void WebsocketListener(WebsocketMessageEvent event){ 3 System.out.println("监听到WebsocketMessageEvent事件"); 4  } 5 }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄