国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Spring整合websocket整合應(yīng)用示例(下)

2019-11-26 14:27:38
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

在Spring整合websocket整合應(yīng)用示例(上)文章中,我們已經(jīng)實(shí)現(xiàn)了websocket,但還有一個(gè)核心的業(yè)務(wù)實(shí)現(xiàn)類沒(méi)有實(shí)現(xiàn),這里我們就實(shí)現(xiàn)這個(gè)業(yè)務(wù)核心類,因?yàn)槔戏騾⑴c的這個(gè)系統(tǒng)使用websocket發(fā)送消息,所以其實(shí)現(xiàn)就是如何發(fā)送消息了。

7. NewsListenerImpl的實(shí)現(xiàn)

package cn.bridgeli.websocket;import com.google.gson.Gson;import com.google.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 : 站內(nèi)消息監(jiān)聽器實(shí)現(xiàn)* @Date : 16-3-7*/@Componentpublic 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();//任務(wù)調(diào)度private SchedulerFactory sf = new StdSchedulerFactory();@Autowiredprivate PlatNewsService platNewsService;@Overridepublic void afterPersist(PlatNewsVo platNewsVo) {logger.info("監(jiān)聽到有新消息添加。。。");logger.info("新消息為:"+gson.toJson(platNewsVo));//啟動(dòng)線程if(null != platNewsVo && !StringUtils.isBlank(platNewsVo.getCurrentoperatoremail())){//如果是定時(shí)消息if(platNewsVo.getNewsType() == PlatNewsCategoryType.TIMING_TIME.getCategoryId()){startTimingTask(platNewsVo); //定時(shí)推送}else{//立即推送executorService.execute(new AfterConnectionEstablishedTask(platNewsVo.getCurrentoperatoremail()));}}}@Overridepublic void afterConnectionEstablished(String email) {logger.info("建立websocket連接后推送新消息。。。");if(!StringUtils.isBlank(email)){executorService.execute(new AfterConnectionEstablishedTask(email));}}/*** @Description : 如果新添加了定時(shí)消息,啟動(dòng)定時(shí)消息任務(wù)* @param platNewsVo*/private void startTimingTask(PlatNewsVo platNewsVo){logger.info("開始定時(shí)推送消息任務(wù)。。。");Date timingTime = platNewsVo.getTimingTime();if(null == timingTime){logger.info("定時(shí)消息時(shí)間為null。");return;}logger.info("定時(shí)推送任務(wù)時(shí)間為:"+DateUtil.date2String(timingTime));JobDetail jobDetail= JobBuilder.newJob(TimingJob.class).withIdentity(platNewsVo.getCurrentoperatoremail()+"定時(shí)消息"+platNewsVo.getId(), "站內(nèi)消息").build();//傳遞參數(shù)jobDetail.getJobDataMap().put("platNewsService",platNewsService);jobDetail.getJobDataMap().put("userEmail",platNewsVo.getCurrentoperatoremail());Trigger trigger= TriggerBuilder.newTrigger().withIdentity("定時(shí)消息觸發(fā)"+platNewsVo.getId(), "站內(nèi)消息").startAt(timingTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(0) //時(shí)間間隔.withRepeatCount(0) //重復(fù)次數(shù)).build();//啟動(dòng)定時(shí)任務(wù)try {Scheduler sched = sf.getScheduler();sched.scheduleJob(jobDetail,trigger);if(!sched.isShutdown()){sched.start();}} catch (SchedulerException e) {logger.info(e.toString());}logger.info("完成開啟定時(shí)推送消息任務(wù)。。。");}/*** @Description : 建立websocket鏈接后的推送線程*/class AfterConnectionEstablishedTask implements Runnable{String email ;public AfterConnectionEstablishedTask(String email){this.email = email;}@Overridepublic 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);//更新推送時(shí)間userSocketVo.setLastSendTime(DateUtil.getNowDate());logger.info("完成推送新消息給用戶:"+userSocketVo.getUserEmail()+"。。。");}} catch (IOException e) {logger.error(e.toString());logger.info("站內(nèi)消息推送失敗。。。"+e.toString());}}}logger.info("結(jié)束推送消息給"+email+"。。。");}}}

這個(gè)類就是websocket的核心業(yè)務(wù)的實(shí)現(xiàn),其具體肯定和業(yè)務(wù)相關(guān),由于業(yè)務(wù)的不同,實(shí)現(xiàn)肯定不同,因?yàn)槔戏騾⑴c的系統(tǒng)是發(fā)送消息,所以里面最核心的一句就是:

userSocketVo.getWebSocketSession().sendMessage(reMessage);

通過(guò)WebSocketSession的sendMessage方法把我們的消息發(fā)送出去。另外,這主要是后端的實(shí)現(xiàn),至于前端的實(shí)現(xiàn),因?yàn)槔戏蚴呛蠖顺绦蛟潮容^關(guān)注后端,所以前端就不多做介紹了,大家可以自己去網(wǎng)上查資料。最后需要說(shuō)明的是,老夫之前搜一些學(xué)習(xí)資料的時(shí)候,發(fā)現(xiàn)老夫該同事的寫法和有一篇文章幾乎一樣,我想該同事應(yīng)該是參考了這篇文章,所以列在下面,算作參考資料。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 阜南县| 昌吉市| 丹巴县| 灵川县| 锡林浩特市| 荣昌县| 景宁| 周口市| 陇西县| 永修县| 通城县| 渝中区| 鄂托克前旗| 东乌珠穆沁旗| 兴仁县| 大埔县| 正阳县| 湟源县| 梅州市| 屏南县| 息烽县| 新和县| 奈曼旗| 义马市| 翁源县| 巴青县| 友谊县| 新干县| 安庆市| 仙居县| 鞍山市| 静安区| 巴林右旗| 石狮市| 准格尔旗| 江永县| 民丰县| 吉隆县| 宜州市| 襄樊市| 赣州市|