SpringBoot整合WebSocket實現後臺向前端推送資訊的示例
阿新 • • 發佈:2020-12-28
前言
在一次專案開發中,使用到了Netty網路應用框架,以及MQTT進行訊息資料的收發,這其中需要後臺來將獲取到的訊息主動推送給前端,於是就使用到了MQTT,特此記錄一下。
一、什麼是websocket?
WebSocket協議是基於TCP的一種新的網路協議。它實現了客戶端與伺服器全雙工通訊,學過計算機網路都知道,既然是全雙工,就說明了伺服器可以主動傳送資訊給客戶端。這與我們的推送技術或者是多人線上聊天的功能不謀而合。
為什麼不使用HTTP 協議呢?這是因為HTTP是單工通訊,通訊只能由客戶端發起,客戶端請求一下,伺服器處理一下,這就太麻煩了。於是websocket應運而生。
下面我們就直接開始使用Springboot開始整合。以下案例都在我自己的電腦上測試成功,你可以根據自己的功能進行修改即可。
我的專案結構如下:
二、使用步驟
1.新增依賴
Maven依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2.啟用Springboot對WebSocket的支援
啟用WebSocket的支援也是很簡單,幾句程式碼搞定:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @ Auther: 馬超偉 * @ Date: 2020/06/16/14:35 * @ Description: 開啟WebSocket支援 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3.核心配置:WebSocketServer
因為WebSocket是類似客戶端服務端的形式(採用ws協議),那麼這裡的WebSocketServer其實就相當於一個ws協議的Controller
- @ ServerEndpoint 註解是一個類層次的註解,它的功能主要是將目前的類定義成一個websocket伺服器端,註解的值將被用於監聽使用者連線的終端訪問URL地址,客戶端可以通過這個URL來連線到WebSocket伺服器端
- 新建一個ConcurrentHashMap webSocketMap 用於接收當前userId的WebSocket,方便傳遞之間對userId進行推送訊息。
下面是具體業務程式碼:
package cc.mrbird.febs.external.webScoket; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; /** * Created with IntelliJ IDEA. * @ Auther: 馬超偉 * @ Date: 2020/06/16/14:35 * @ Description: * @ ServerEndpoint 註解是一個類層次的註解,它的功能主要是將目前的類定義成一個websocket伺服器端,* 註解的值將被用於監聽使用者連線的終端訪問URL地址,客戶端可以通過這個URL來連線到WebSocket伺服器端 */ @Component @Slf4j @Service @ServerEndpoint("/api/websocket/{sid}") public class WebSocketServer { //靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。 private static int onlineCount = 0; //concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料 private Session session; //接收sid private String sid = ""; /** * 連線建立成功呼叫的方法 */ @OnOpen public void onOpen(Session session,@PathParam("sid") String sid) { this.session = session; webSocketSet.add(this); //加入set中 this.sid = sid; addOnlineCount(); //線上數加1 try { sendMessage("conn_success"); log.info("有新視窗開始監聽:" + sid + ",當前線上人數為:" + getOnlineCount()); } catch (IOException e) { log.error("websocket IO Exception"); } } /** * 連線關閉呼叫的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //線上數減1 //斷開連線情況下,更新主機板佔用情況為釋放 log.info("釋放的sid為:"+sid); //這裡寫你 釋放的時候,要處理的業務 log.info("有一連線關閉!當前線上人數為" + getOnlineCount()); } /** * 收到客戶端訊息後呼叫的方法 * @ Param message 客戶端傳送過來的訊息 */ @OnMessage public void onMessage(String message,Session session) { log.info("收到來自視窗" + sid + "的資訊:" + 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.printStackTrace(); } /** * 實現伺服器主動推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群發自定義訊息 */ public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException { log.info("推送訊息到視窗" + sid + ",推送內容:" + message); for (WebSocketServer item : webSocketSet) { try { //這裡可以設定只推送給這個sid的,為null則全部推送 if (sid == null) { // item.sendMessage(message); } else if (item.sid.equals(sid)) { 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--; } public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() { return webSocketSet; } }
4.測試Controller
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created with IntelliJ IDEA. * * @ Auther: 馬超偉 * @ Date: 2020/06/16/14:38 * @ Description: */ @Controller("web_Scoket_system") @RequestMapping("/api/socket") public class SystemController { //頁面請求 @GetMapping("/index/{userId}") public ModelAndView socket(@PathVariable String userId) { ModelAndView mav = new ModelAndView("/socket1"); mav.addObject("userId",userId); return mav; } //推送資料介面 @ResponseBody @RequestMapping("/socket/push/{cid}") public Map pushToWeb(@PathVariable String cid,String message) { Map<String,Object> result = new HashMap<>(); try { WebSocketServer.sendInfo(message,cid); result.put("code",cid); result.put("msg",message); } catch (IOException e) { e.printStackTrace(); } return result; } }
5.測試頁面index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Java後端WebSocket的Tomcat實現</title> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="main" style="width: 1200px;height:800px;"></div> Welcome<br/><input id="text" type="text" /> <button onclick="send()">傳送訊息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket連線</button> <hr/> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支援WebSocket if('WebSocket' in window) { //改成你的地址 websocket = new WebSocket("ws://192.168.100.196:8082/api/websocket/100"); } else { alert('當前瀏覽器 Not support websocket') } //連線發生錯誤的回撥方法 websocket.onerror = function() { setMessageInnerHTML("WebSocket連線發生錯誤"); }; //連線成功建立的回撥方法 websocket.onopen = function() { setMessageInnerHTML("WebSocket連線成功"); } var U01data,Uidata,Usdata //接收到訊息的回撥方法 websocket.onmessage = function(event) { console.log(event); setMessageInnerHTML(event); setechart() } //連線關閉的回撥方法 websocket.onclose = function() { setMessageInnerHTML("WebSocket連線關閉"); } //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function() { closeWebSocket(); } //將訊息顯示在網頁上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //關閉WebSocket連線 function closeWebSocket() { websocket.close(); } //傳送訊息 function send() { var message = document.getElementById('text').value; websocket.send('{"msg":"' + message + '"}'); setMessageInnerHTML(message + " "); } </script> </html>
6.結果展示
後臺:
如果有連線請求
前臺顯示:
總結
這中間我遇到一個問題,就是說WebSocket啟動的時候優先於spring容器,從而導致在WebSocketServer中呼叫業務Service會報空指標異常
所以需要在WebSocketServer中將所需要用到的service給靜態初始化一下:
如圖所示:
還需要做如下配置:
到此這篇關於SpringBoot整合WebSocket實現後臺向前端推送資訊的示例的文章就介紹到這了,更多相關SpringBoot整合WebSocket 內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!