In the spring consolidation WebSocket Example (above) article, we have implemented the WebSocket, but there is still a core business implementation class is not implemented, here we implement this business core class, because the old couple involved in the system using WebSocket to send messages, So the implementation is how to send the message.
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-Station message listener implementation * @Date: 16-3-7 * * @Component public class Newslistenerimpl implements newslistener{Priva
Te 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 Scheduler private Schedulerfactory SF = new Stdschedulerfactory ();
@Autowired private Platnewsservice Platnewsservice; @Override public void Afterpersist (Platnewsvo platnewsvo) {logger.info ("I heard a new message added ...
");
Logger.info ("New message is:" +gson.tojson (PLATNEWSVO)); Start thread if (null!= PLATNEWSVO &&!) Stringutils.isblank (Platnewsvo.getcurrentoperatoremail ()) {//If it is a timed message if (platnewsvo.getnewstype () = =
PlatNewsCategoryType.TIMING_TIME.getCategoryId ()) {starttimingtask (PLATNEWSVO);//timed push}else{//immediate push
Executorservice.execute (New Afterconnectionestablishedtask (Platnewsvo.getcurrentoperatoremail ())); @Override public void AFterconnectionestablished (String email) {logger.info ("push new message after establishing WebSocket connection ...")
"); if (!
Stringutils.isblank (email)) {Executorservice.execute (new Afterconnectionestablishedtask (email));} /** * @Description: If a new timed message is added, start a timed message task * @param PLATNEWSVO/private void Starttimingtask (Platnewsvo platnewsvo) {Logge R.info ("Start scheduled push message task ...")
");
Date timingtime = Platnewsvo.gettimingtime (); if (null = = Timingtime) {logger.info ("timed message time is null.")
");
Return
Logger.info ("Scheduled push task time is:" +dateutil.date2string (Timingtime)); Jobdetail jobdetail= jobbuilder.newjob (timingjob.class). Withidentity (Platnewsvo.getcurrentoperatoremail () + timed message
+platnewsvo.getid (), "in-Station message"). Build ();
Pass parameter Jobdetail.getjobdatamap (). Put ("Platnewsservice", Platnewsservice);
Jobdetail.getjobdatamap (). Put ("UserEmail", Platnewsvo.getcurrentoperatoremail ()); Trigger trigger= Triggerbuilder. Newtrigger (). Withidentity ("timed message Triggers" +platnewsvo.getid (), "in-station messages"). StartAt (Timingtime ). Withschedule (Simpleschedulebuilder.simpleschedule (). withintervalinseconds(0)//time interval. Withrepeatcount (0)//repetition times). Build ();
Start timed task try {Scheduler sched = Sf.getscheduler (); Sched.schedulejob (Jobdetail,trigger); if (!sched.isshutdown ()) {
Sched.start (); } catch (Schedulerexception e) {logger.info (e.tostring ());} logger.info ("Finish opening a scheduled push message task ...")
");
} /** * @Description: Create WebSocket link push thread/class Afterconnectionestablishedtask implements runnable{String email; publi C Afterconnectionestablishedtask (String email) {this.email = email;} @Override public void Run () {logger.info ("Start pushing messages to 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 User:" +usersocketvo.getuseremail () + "... ");
}
} catch (IOException e) {logger.error (e.tostring ()); Logger.info ("station message push failed ...")
"+e.tostring ());}}} Logger.info ("End push message to +email+" ...) ");
}
}
}
This class is the core business of WebSocket, its specific affirmation and business-related, due to the different business, the implementation is certainly different, because the old couple involved in the system is to send messages, so inside the most central sentence is:
Usersocketvo.getwebsocketsession (). SendMessage (Remessage);
Send our messages through the Websocketsession SendMessage method. In addition, this is mainly the implementation of the backend, as for the front-end implementation, because the old is the back-end program Ape more concerned about the back end, so the front-end does not do more introduction, we can go to the Internet to check the data. Finally need to explain that the old couple before the search for some learning materials, found that the colleague's writing and have an article almost the same, I think the colleague should be referring to this article, so listed below, counted as reference.