In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use spring boot+WebSocket to achieve background active message push function". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use spring boot+WebSocket to achieve background active message push function".
Foreword:
Make sure that the production environment is compatible / supported when using this webscoket! Make sure that the production environment is compatible / supported when using this webscoket! Make sure that the production environment is compatible / supported when using this webscoket! Mainly the compatibility and support of tomcat.
There is a need:
APP users generate an operation that needs to be perceived by some people in the background management system (represented as a page message).
The earliest version is the background management system rotation training, every period of time rotation training, because the news is important, every few seconds to check. This is obviously very indecent! It consumes a lot of resources, and most of the requests are useless (no data can be found) and are very thin.
Later, I wanted to deal with this logic by pushing messages. The user generates a target operation in app, that is, a message is generated and pushed to the corresponding user of the background management system.
Then I looked for all kinds of materials. At first, my colleagues recommended dwz, but later found that it was not very suitable for the current project (maybe it can be achieved, but I just don't know how to implement it).
Later learned about WebSocket, read a lot of documents on the Internet are similar to chat room scenes, some different. Here, I mainly focus on the active push of the server, which is triggered by the server.
Scenarios that WebSocket can mainly implement:
1. Web chat room
2. Real-time notification of server messages
There should be many ways to use WebSocket, so use the implementation in the tomcat8+h6 environment under this introduction.
Don't say much, go directly to the code, if you want to know more about WebSocket, please consult the relevant introduction.
1.pom
Org.springframework.boot spring-boot-starter-websocket
two。 Create a websocket endpoint using @ ServerEndpoint
@ Configurationpublic class WebSocketConfig {@ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();}}
3. The specific implementation class can choose whether url should take parameters or not.
Package com.star.manager.service;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component @ Slf4j//@ServerEndpoint ("/ websocket/ {user}") @ ServerEndpoint (value = "/ websocket") @ Componentpublic class WebSocketServer {/ / static variable to record the current number of online connections. It should be designed to be thread safe. Private static int onlineCount = 0; / the thread-safe Set of the concurrent package, which is used to store the corresponding MyWebSocket object for each client. Private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet (); / / A connection session with a client that is needed to send data to the client private Session session; / * the method called successfully for connection establishment * / @ OnOpen public void onOpen (Session session) {this.session = session; webSocketSet.add (this); / / join addOnlineCount () in set () / / online plus 1 log.info ("there is a new connection to join! The current number of online users is "+ getOnlineCount (); try {sendMessage (" connected successfully ");} catch (IOException e) {log.error (" websocket IO exception ") }} / execute / / @ OnOpen / / public void onOpen (@ PathParam ("user") String user, Session session) {/ / currentUser = user; / / System.out.println ("Connected..." + session.getId ()) when the connection is opened / /} / * connection closes the method called * / @ OnClose public void onClose () {webSocketSet.remove (this); / / removes subOnlineCount () from set; / / the number of lines minus 1 log.info ("A connection is closed! The current number of people online is "+ getOnlineCount ();} / * the method called after receiving the client message * * @ param message client sent message * / @ OnMessage public void onMessage (String message, Session session) {log.info (" message from client: "+ message) / / for (WebSocketServer item: webSocketSet) {try {item.sendMessage (message);} catch (IOException e) {e.printStackTrace () } / * * @ param session * @ param error * / @ OnError public void onError (Session session, Throwable error) {log.error ("error occurs"); error.printStackTrace ();} public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message) Group custom messages * * / public static void sendInfo (String message) throws IOException {log.info (message); for (WebSocketServer item: webSocketSet) {try {item.sendMessage (message);} catch (IOException e) {continue Public static synchronized int getOnlineCount () {return onlineCount;} public static synchronized void addOnlineCount () {WebSocketServer.onlineCount++;} public static synchronized void subOnlineCount () {WebSocketServer.onlineCount--;}}
Generate a message: there are many scenarios for generating messages, http (s), scheduled tasks, mq, etc., which post a controller code for a httpq request
@ RequestMapping (value= "/ pushVideoListToWeb", method=RequestMethod.POST,consumes = "application/json") public @ ResponseBody Map pushVideoListToWeb (@ RequestBody Map param) {Map result = new HashMap (); try {WebSocketServer.sendInfo ("incoming new customers, sltAccountId:" + CommonUtils.getValue (param, "sltAccountId"); result.put ("operationResult", true) } catch (IOException e) {result.put ("operationResult", true);} return result;}
I have thickened the important parts, mainly this section, using this method, we can realize the active push of the server.
Public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message);
4.js (html will not write, just find someone who can trigger this js)
/ / socket = new WebSocket ("ws://localhost:9094/starManager/websocket/ Zhang San"); var socket; if (typeof (WebSocket) = = "undefined") {console.log ("your browser does not support WebSocket");} else {console.log ("your browser supports WebSocket") / / implement the WebSocket object, specify the address of the server to be connected to establish a connection with the port / / socket = new WebSocket ("ws://localhost:9094/starManager/websocket/ Zhang San") socket = new WebSocket ("ws://localhost:9094/starManager/websocket") / / Open event socket.onopen = function () {console.log ("Socket is open"); / / socket.send ("this is a message from the client" + location.href + new Date ());} / / get the message event socket.onmessage = function (msg) {console.log (msg.data); / / find the message to enter the background to get getCallingList ();} / / close event socket.onclose = function () {console.log ("Socket closed");}; / / error event socket.onerror = function () {alert ("Socket has an error") } $(window) .unload (function () {socket.close ();}) / / $("# btnSend") .click (function () {/ / socket.send ("this is a message from the client" + location.href + new Date ()); / /}) / $("# btnClose") .click (function () {/ / socket.close (); / /});}
In a nutshell:
Through front-end code
Socket = new WebSocket ("ws://localhost:9094/starManager/websocket")
Where starManager is the project name and / webscoket is the access path name
To establish a connection, the front end calls scoket.open () to make the background add an element to the static member variable webSocketSet, which is equivalent to a cache. The background service invokes sendMessage
(specify a user, direct) or sendInfo (traverse webSocketSet to send one by one, similar to mass sending) method, you can push messages to logged-in clients.
That's all the code. I can run with this code. When doing the page reported 404 and other errors, if it is also spring boot+h6, carefully check and my code is not different, plus configuration path is there is ok, the problem should not be big.
Thank you for your reading, the above is the content of "how to use spring boot+WebSocket to achieve background active message push function". After the study of this article, I believe you have a deeper understanding of how to use spring boot+WebSocket to achieve background active message push function, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.