在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Spring整合websocket整合应用示例(下)

2016-7-29 15:41| 发布者: zhangjf| 查看: 571| 评论: 0

摘要: 在Spring整合websocket整合应用示例(上)文章中,我们已经实现了websocket,但还有一个核心的业务实现类没有实现,这里我们就实现这个业务核心类,因为老夫参与的这个系统使用websocket发送消息,所以其实现就是如 ...

在Spring整合websocket整合应用示例(上)文章中,我们已经实现了websocket,但还有一个核心的业务实现类没有实现,这里我们就实现这个业务核心类,因为老夫参与的这个系统使用websocket发送消息,所以其实现就是如何发送消息了。

7. NewsListenerImpl的实现

  1. package cn.bridgeli.websocket;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. import com.lagou.common.base.util.date.DateUtil;
  5. import com.lagou.platform.news.api.enumeration.PlatNewsCategoryType;
  6. import com.lagou.platform.news.web.dao.ext.model.PlatNewsVo;
  7. import com.lagou.platform.news.web.dao.ext.model.SearchCondition;
  8. import com.lagou.platform.news.web.quartz.impl.TimingJob;
  9. import com.lagou.platform.news.web.service.PlatNewsService;
  10. import org.apache.commons.lang.StringUtils;
  11. import org.json.simple.JSONArray;
  12. import org.json.simple.JSONObject;
  13. import org.quartz.*;
  14. import org.quartz.impl.StdSchedulerFactory;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import org.springframework.beans.factory.annotation.Autowired;
  18. import org.springframework.stereotype.Component;
  19. import org.springframework.web.socket.TextMessage;
  20. import java.io.IOException;
  21. import java.util.Date;
  22. import java.util.List;
  23. import java.util.concurrent.ExecutorService;
  24. import java.util.concurrent.Executors;
  25. /**
  26. * @Description : 站内消息监听器实现
  27. * @Date : 16-3-7
  28. */
  29. @Component
  30. public class NewsListenerImpl implements NewsListener{
  31. private static final Logger logger = LoggerFactory.getLogger(NewsListenerImpl.class);
  32. Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
  33. //线程池
  34. private ExecutorService executorService = Executors.newCachedThreadPool();
  35. //任务调度
  36. private SchedulerFactory sf = new StdSchedulerFactory();
  37. @Autowired
  38. private PlatNewsService platNewsService;
  39. @Override
  40. public void afterPersist(PlatNewsVo platNewsVo) {
  41. logger.info("监听到有新消息添加。。。");
  42. logger.info("新消息为:"+gson.toJson(platNewsVo));
  43. //启动线程
  44. if(null != platNewsVo && !StringUtils.isBlank(platNewsVo.getCurrentoperatoremail())){
  45. //如果是定时消息
  46. if(platNewsVo.getNewsType() == PlatNewsCategoryType.TIMING_TIME.getCategoryId()){
  47. startTimingTask(platNewsVo); //定时推送
  48. }else{
  49. //立即推送
  50. executorService.execute(new AfterConnectionEstablishedTask(platNewsVo.getCurrentoperatoremail()));
  51. }
  52. }
  53. }
  54. @Override
  55. public void afterConnectionEstablished(String email) {
  56. logger.info("建立websocket连接后推送新消息。。。");
  57. if(!StringUtils.isBlank(email)){
  58. executorService.execute(new AfterConnectionEstablishedTask(email));
  59. }
  60. }
  61. /**
  62. * @Description : 如果新添加了定时消息,启动定时消息任务
  63. * @param platNewsVo
  64. */
  65. private void startTimingTask(PlatNewsVo platNewsVo){
  66. logger.info("开始定时推送消息任务。。。");
  67. Date timingTime = platNewsVo.getTimingTime();
  68. if(null == timingTime){
  69. logger.info("定时消息时间为null。");
  70. return;
  71. }
  72. logger.info("定时推送任务时间为:"+DateUtil.date2String(timingTime));
  73. JobDetail jobDetail= JobBuilder.newJob(TimingJob.class)
  74. .withIdentity(platNewsVo.getCurrentoperatoremail()+"定时消息"+platNewsVo.getId(), "站内消息")
  75. .build();
  76. //传递参数
  77. jobDetail.getJobDataMap().put("platNewsService",platNewsService);
  78. jobDetail.getJobDataMap().put("userEmail",platNewsVo.getCurrentoperatoremail());
  79. Trigger trigger= TriggerBuilder
  80. .newTrigger()
  81. .withIdentity("定时消息触发"+platNewsVo.getId(), "站内消息")
  82. .startAt(timingTime)
  83. .withSchedule(SimpleScheduleBuilder.simpleSchedule()
  84. .withIntervalInSeconds(0) //时间间隔
  85. .withRepeatCount(0) //重复次数
  86. )
  87. .build();
  88. //启动定时任务
  89. try {
  90. Scheduler sched = sf.getScheduler();
  91. sched.scheduleJob(jobDetail,trigger);
  92. if(!sched.isShutdown()){
  93. sched.start();
  94. }
  95. } catch (SchedulerException e) {
  96. logger.info(e.toString());
  97. }
  98. logger.info("完成开启定时推送消息任务。。。");
  99. }
  100. /**
  101. * @Description : 建立websocket链接后的推送线程
  102. */
  103. class AfterConnectionEstablishedTask implements Runnable{
  104. String email ;
  105. public AfterConnectionEstablishedTask(String email){
  106. this.email = email;
  107. }
  108. @Override
  109. public void run() {
  110. logger.info("开始推送消息给用户:"+email+"。。。");
  111. if(!StringUtils.isBlank(email)){
  112. SearchCondition searchCondition = new SearchCondition();
  113. searchCondition.setOperatorEmail(email);
  114. JSONArray jsonArray = new JSONArray();
  115. for(PlatNewsCategoryType type : PlatNewsCategoryType.values()){
  116. searchCondition.setTypeId(type.getCategoryId());
  117. int count = platNewsService.countPlatNewsByExample(searchCondition);
  118. JSONObject object = new JSONObject();
  119. object.put("name",type.name());
  120. object.put("description",type.getDescription());
  121. object.put("count",count);
  122. jsonArray.add(object);
  123. }
  124. if(null != jsonArray && jsonArray.size()>0){
  125. UserSocketVo userSocketVo = WSSessionLocalCache.get(email);
  126. TextMessage reMessage = new TextMessage(gson.toJson(jsonArray));
  127. try {
  128. if(null != userSocketVo){
  129. //推送消息
  130. userSocketVo.getWebSocketSession().sendMessage(reMessage);
  131. //更新推送时间
  132. userSocketVo.setLastSendTime(DateUtil.getNowDate());
  133. logger.info("完成推送新消息给用户:"+userSocketVo.getUserEmail()+"。。。");
  134. }
  135. } catch (IOException e) {
  136. logger.error(e.toString());
  137. logger.info("站内消息推送失败。。。"+e.toString());
  138. }
  139. }
  140. }
  141. logger.info("结束推送消息给"+email+"。。。");
  142. }
  143. }
  144. }
复制代码

这个类就是websocket的核心业务的实现,其具体肯定和业务相关,由于业务的不同,实现肯定不同,因为老夫参与的系统是发送消息,所以里面最核心的一句就是:

  1. userSocketVo.getWebSocketSession().sendMessage(reMessage);
复制代码

通过WebSocketSession的sendMessage方法把我们的消息发送出去。另外,这主要是后端的实现,至于前端的实现,因为老夫是后端程序猿比较关注后端,所以前端就不多做介绍了,大家可以自己去网上查资料。最后需要说明的是,老夫之前搜一些学习资料的时候,发现老夫该同事的写法和有一篇文章几乎一样,我想该同事应该是参考了这篇文章,所以列在下面,算作参考资料。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 09:12

Copyright 2015-2025 djqfx

返回顶部