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 }

转载于:https://www.cnblogs.com/Asp1rant/p/10673095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值