事件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 }
转自:
https://www.cnblogs.com/Asp1rant/p/10673095.html