Spring整合websocket整合運用示例(下)。本站提示廣大學習愛好者:(Spring整合websocket整合運用示例(下))文章只能為提供參考,不一定能成為您想要的結果。以下是Spring整合websocket整合運用示例(下)正文
在Spring整合websocket整合運用示例(上)文章中,我們曾經完成了websocket,但還有一個焦點的營業完成類沒有完成,這裡我們就完成這個營業焦點類,由於老漢介入的這個體系應用websocket發送新聞,所以其完成就是若何發送新聞了。
7. NewsListenerImpl的完成
package cn.bridgeli.websocket; import com.谷歌.gson.Gson; import com.谷歌.gson.GsonBuilder; import com.lagou.common.base.util.date.DateUtil; import com.lagou.platform.news.api.enumeration.PlatNewsCategoryType; import com.lagou.platform.news.web.dao.ext.model.PlatNewsVo; import com.lagou.platform.news.web.dao.ext.model.SearchCondition; import com.lagou.platform.news.web.quartz.impl.TimingJob; import com.lagou.platform.news.web.service.PlatNewsService; import org.apache.commons.lang.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Description : 站內新聞監聽器完成 * @Date : 16-3-7 */ @Component public class NewsListenerImpl implements NewsListener{ private static final Logger logger = LoggerFactory.getLogger(NewsListenerImpl.class); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); //線程池 private ExecutorService executorService = Executors.newCachedThreadPool(); //義務調劑 private SchedulerFactory sf = new StdSchedulerFactory(); @Autowired private PlatNewsService platNewsService; @Override public void afterPersist(PlatNewsVo platNewsVo) { logger.info("監聽到有新新聞添加。。。"); logger.info("新新聞為:"+gson.toJson(platNewsVo)); //啟動線程 if(null != platNewsVo && !StringUtils.isBlank(platNewsVo.getCurrentoperatoremail())){ //假如是准時新聞 if(platNewsVo.getNewsType() == PlatNewsCategoryType.TIMING_TIME.getCategoryId()){ startTimingTask(platNewsVo); //准時推送 }else{ //立刻推送 executorService.execute(new AfterConnectionEstablishedTask(platNewsVo.getCurrentoperatoremail())); } } } @Override public void afterConnectionEstablished(String email) { logger.info("樹立websocket銜接後推送新新聞。。。"); if(!StringUtils.isBlank(email)){ executorService.execute(new AfterConnectionEstablishedTask(email)); } } /** * @Description : 假如新添加了准時新聞,啟動准時新聞義務 * @param platNewsVo */ private void startTimingTask(PlatNewsVo platNewsVo){ logger.info("開端准時推送新聞義務。。。"); Date timingTime = platNewsVo.getTimingTime(); if(null == timingTime){ logger.info("准時新聞時光為null。"); return; } logger.info("准時推送義務時光為:"+DateUtil.date2String(timingTime)); JobDetail jobDetail= JobBuilder.newJob(TimingJob.class) .withIdentity(platNewsVo.getCurrentoperatoremail()+"准時新聞"+platNewsVo.getId(), "站內新聞") .build(); //傳遞參數 jobDetail.getJobDataMap().put("platNewsService",platNewsService); jobDetail.getJobDataMap().put("userEmail",platNewsVo.getCurrentoperatoremail()); Trigger trigger= TriggerBuilder .newTrigger() .withIdentity("准時新聞觸發"+platNewsVo.getId(), "站內新聞") .startAt(timingTime) .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(0) //時光距離 .withRepeatCount(0) //反復次數 ) .build(); //啟動准時義務 try { Scheduler sched = sf.getScheduler(); sched.scheduleJob(jobDetail,trigger); if(!sched.isShutdown()){ sched.start(); } } catch (SchedulerException e) { logger.info(e.toString()); } logger.info("完成開啟准時推送新聞義務。。。"); } /** * @Description : 樹立websocket鏈接後的推送線程 */ class AfterConnectionEstablishedTask implements Runnable{ String email ; public AfterConnectionEstablishedTask(String email){ this.email = email; } @Override public void run() { logger.info("開端推送新聞給用戶:"+email+"。。。"); if(!StringUtils.isBlank(email)){ SearchCondition searchCondition = new SearchCondition(); searchCondition.setOperatorEmail(email); JSONArray jsonArray = new JSONArray(); for(PlatNewsCategoryType type : PlatNewsCategoryType.values()){ searchCondition.setTypeId(type.getCategoryId()); int count = platNewsService.countPlatNewsByExample(searchCondition); JSONObject object = new JSONObject(); object.put("name",type.name()); object.put("description",type.getDescription()); object.put("count",count); jsonArray.add(object); } if(null != jsonArray && jsonArray.size()>0){ UserSocketVo userSocketVo = WSSessionLocalCache.get(email); TextMessage reMessage = new TextMessage(gson.toJson(jsonArray)); try { if(null != userSocketVo){ //推送新聞 userSocketVo.getWebSocketSession().sendMessage(reMessage); //更新推送時光 userSocketVo.setLastSendTime(DateUtil.getNowDate()); logger.info("完成推送新新聞給用戶:"+userSocketVo.getUserEmail()+"。。。"); } } catch (IOException e) { logger.error(e.toString()); logger.info("站內新聞推送掉敗。。。"+e.toString()); } } } logger.info("停止推送新聞給"+email+"。。。"); } } }
這個類就是websocket的焦點營業的完成,其詳細確定和營業相干,因為營業的分歧,完成確定分歧,由於老漢介入的體系是發送新聞,所以外面最焦點的一句就是:
userSocketVo.getWebSocketSession().sendMessage(reMessage);
經由過程WebSocketSession的sendMessage辦法把我們的新聞發送出去。別的,這重要是後真個完成,至於前真個完成,由於老漢是後端法式猿比擬存眷後端,所之前端就不多做引見了,年夜家可以本身去網上查材料。最初須要解釋的是,老漢之前搜一些進修材料的時刻,發明老漢該同事的寫法和有一篇文章簡直一樣,我想該同事應當是參考了這篇文章,所以列鄙人面,算作參考材料。