In the Spring Integration Websocket Integration Application Example (Part 1), we have implemented websocket, but there is still a core business implementation class that has not been implemented. Here we implement this business core class. Because the system I participated in uses websocket to send messages, the implementation is how to send messages.
7. Implementation of NewsListenerImpl
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 : In-site message listener implementation* @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();//Thread pool private ExecutorService executorService = Executors.newCachedThreadPool();//Task SchedulerFactory sf = new StdSchedulerFactory();@Autowiredprivate PlatNewsService platNewsService;@Overridepublic void afterPersist(PlatNewsVo platNewsVo) {logger.info("A listened to a new message added. . . ");logger.info("New message is:"+gson.toJson(platNewsVo));//Start the thread if(null != platNewsVo && !StringUtils.isBlank(platNewsVo.getCurrentooperatoremail())){//If it is a timed message if(platNewsVo.getNewsType() == PlatNewsCategoryType.TIMING_TIME.getCategoryId()){startTimingTask(platNewsVo); //Scheduled push}else{//Push executorService.execute(new AfterConnectionEstablishedTask(platNewsVo.getCurrentooperatoremail()));}}}@Overridepublic void afterConnectionEstablished(String email) {logger.info("Push a new message after establishing a websocket connection..."); if(!StringUtils.isBlank(email)){executorService.execute(new AfterConnectionEstablishedTask(email));}}/*** @Description: If a new timed message is added, start the timed message task* @param platNewsVo*/private void startTimingTask(PlatNewsVo platNewsVo){logger.info("Start the timed push message task...");Date timingTime = platNewsVo.getTimingTime();if(null == timingTime){logger.info("Timed message time is null.");return;}logger.info("Timed push task time is: "+DateUtil.date2String(timingTime));JobDetail jobDetail= JobBuilder.newJob(TimingJob.class).withIdentity(platNewsVo.getCurrentooperatoremail()+"timed message"+platNewsVo.getId(), "Site Message").build();//Pass the parameters jobDetail.getJobDataMap().put("platNewsService",platNewsService);jobDetail.getJobDataMap().put("userEmail",platNewsVo.getCurrentooperatoremail());Trigger trigger= TriggerBuilder.newTrigger().withIdentity("Timer message trigger"+platNewsVo.getId(), "In-site message").startAt(timingTime).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(0) //Time interval.withRepeatCount(0) //RepeatCount(0) //Number of repetitions).build();//Start the timing task try {Scheduler sched = sf.getScheduler();sched.scheduleJob(jobDetail,trigger);if(!sched.isShutdown()){sched.start();}} catch (SchedulerException e) {logger.info(e.toString());}logger.info("Complete the start of the timed push message task. . . ");}/*** @Description : Push thread after establishing a websocket link */class AfterConnectionEstablishedTask implements Runnable{String email ;public AfterConnectionEstablishedTask(String email){this.email = email;}@Overridepublic void run() {logger.info("Start push messages to the user: "+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){//Push message userSocketVo.getWebSocketSession().sendMessage(reMessage);//Update push time userSocketVo.setLastSendTime(DateUtil.getNowDate());logger.info("Complete push new message to the user: "+userSocketVo.getUserEmail()+". . . ");}} catch (IOException e) {logger.error(e.toString());logger.info("In-site message push failed... "+e.toString());}}}logger.info("End push message to "+email+"....");}}}This class is the implementation of the core business of websocket. Its specific certainty is related to the business. Due to different business, the implementation is definitely different. Because the system I participated in is sending messages, the most core sentence is:
userSocketVo.getWebSocketSession().sendMessage(reMessage);
Send our message through the sendMessage method of WebSocketSession. In addition, this is mainly the implementation of the backend. As for the implementation of the frontend, because I am a backend programmer, I will pay more attention to the backend, so I won’t introduce the frontend. You can check the information online by yourself. Finally, when I searched for some study materials before, I found that my colleague's writing style was almost the same as an article. I think the colleague should have referenced this article, so it is listed below and counted as reference materials.