- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- springboot簡(jiǎn)單接入websocket的操作方法
最近一個(gè)項目又重啟了,之前支付了要手動(dòng)點(diǎn)擊已付款,所以這次想把這個(gè)不友好體驗干掉。另外以后的掃碼登錄什么的都需要這個(gè)服務(wù)支持。之前掃碼登錄這塊用的mqtt,時(shí)間上是直接把mqtt的連接信息返回給前端。前端連接mqtt服務(wù),消費信息。這次不想這樣弄了,準備接入websocket。
我這里是springBoot2.4.5 + springCloud2020.1.2,這里先從springBoot對接開(kāi)始,逐步再增加深度,不過(guò)可能時(shí)間不夠,就簡(jiǎn)單接入能滿(mǎn)足現在業(yè)務(wù)場(chǎng)景就stop。沒(méi)辦法,從入職就開(kāi)始的一個(gè)項目到現在,要死不活的,沒(méi)有客戶(hù)就不投入,有客戶(hù)就催命,真不知道還能堅持多久。。。。。。
<!-- websocket支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
現在springboot對接websocket就值需要這么簡(jiǎn)單的一個(gè)包了。
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * websocket配置類(lèi) * * @author zhengwen **/ @Slf4j @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
就這一個(gè),里面的bean是用來(lái)掃描Endpoint注解的類(lèi)的。
配置文件都沒(méi)什么好說(shuō)的,簡(jiǎn)單對接用不上,也不用什么調優(yōu)。
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; /** * @author zhengwen **/ @Slf4j @Component @ServerEndpoint("/wsPushMessage/{wsUserId}") public class MyWebSocketSever { /** * 靜態(tài)變量,用來(lái)記錄當前在線(xiàn)連接數。應該把它設計成線(xiàn)程安全的。 */ private static int onlineCount = 0; /** * concurrent包的線(xiàn)程安全Set,用來(lái)存放每個(gè)客戶(hù)端對應的WebSocket對象。 */ private static ConcurrentHashMap<String, MyWebSocketSever> webSocketMap = new ConcurrentHashMap<>(); /** * 與某個(gè)客戶(hù)端的連接會(huì )話(huà),需要通過(guò)它來(lái)給客戶(hù)端發(fā)送數據 */ private Session session; /** * 接收wsUserId */ private String wsUserId = ""; /** * 連接建立成 * 功調用的方法 */ @OnOpen public void onOpen(Session session, @PathParam("wsUserId") String userId) { this.session = session; this.wsUserId = userId; if (webSocketMap.containsKey(userId)) { webSocketMap.remove(userId); //加入set中 webSocketMap.put(userId, this); } else { //加入set中 webSocketMap.put(userId, this); //在線(xiàn)數加1 addOnlineCount(); } log.info("用戶(hù)連接:" + userId + ",當前在線(xiàn)人數為:" + getOnlineCount()); sendMessage("連接成功"); } /** * 連接關(guān)閉 * 調用的方法 */ @OnClose public void onClose() { if (webSocketMap.containsKey(wsUserId)) { webSocketMap.remove(wsUserId); //從set中刪除 subOnlineCount(); } log.info("用戶(hù)退出:" + wsUserId + ",當前在線(xiàn)人數為:" + getOnlineCount()); } /** * 收到客戶(hù)端消 * 息后調用的方法 * * @param message 客戶(hù)端發(fā)送過(guò)來(lái)的消息 **/ @OnMessage public void onMessage(String message, Session session) { log.info("用戶(hù)消息:" + wsUserId + ",報文:" + message); //可以群發(fā)消息 //消息保存到數據庫、redis if (StringUtils.isNotBlank(message)) { try { //解析發(fā)送的報文 JSONObject jsonObject = JSON.parseObject(message); //追加發(fā)送人(防止串改) jsonObject.put("fromUserId", this.wsUserId); String toUserId = jsonObject.getString("toUserId"); //傳送給對應toUserId用戶(hù)的websocket if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) { webSocketMap.get(toUserId).sendMessage(message); } else { //否則不在這個(gè)服務(wù)器上,發(fā)送到mysql或者redis log.error("請求的userId:" + toUserId + "不在該服務(wù)器上"); } } catch (Exception e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用戶(hù)錯誤:" + this.wsUserId + ",原因:" + error.getMessage()); error.printStackTrace(); } }
核心方法就這么幾個(gè),這里面的細節可以自行根據業(yè)務(wù)場(chǎng)景處理,比如給信息增加一個(gè)類(lèi)型,然后搞個(gè)公用方法,根據信息類(lèi)型走不同業(yè)務(wù)邏輯,存庫等等都可以的。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>websocket通訊</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> let socket; function openSocket() { const socketUrl = "ws://localhost:8810/wsPushMessage/" + $("#userId").val(); console.log(socketUrl); if(socket!=null){ socket.close(); socket=null; } socket = new WebSocket(socketUrl); //打開(kāi)事件 socket.onopen = function() { console.log("websocket已打開(kāi)"); }; //獲得消息事件 socket.onmessage = function(msg) { console.log(msg.data); //發(fā)現消息進(jìn)入,開(kāi)始處理前端觸發(fā)邏輯 }; //關(guān)閉事件 socket.onclose = function() { console.log("websocket已關(guān)閉"); }; //發(fā)生了錯誤事件 socket.onerror = function() { console.log("websocket發(fā)生了錯誤"); } } function sendMessage() { socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}'); console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}'); } function closeSocket(){ socket.close(); } </script> <body> <p>【socket開(kāi)啟者的ID信息】:<div><input id="userId" name="userId" type="text" value="10"></div> <p>【客戶(hù)端向服務(wù)器發(fā)送的內容】:<div><input id="toUserId" name="toUserId" type="text" value="20"> <input id="contentText" name="contentText" type="text" value="hello websocket"></div> <p>【開(kāi)啟連接】:<div><a onclick="openSocket()">開(kāi)啟socket</a></div> <p>【發(fā)送信息】:<div><a onclick="sendMessage()">發(fā)送消息</a></div> <p>【關(guān)閉連接】:<div><a onclick="closeSocket()">關(guān)閉socket</a></div> </body> </html>
到此就結束了,基本上就是這么簡(jiǎn)單,我這邊發(fā)送,另一個(gè)網(wǎng)頁(yè)上能收到,而且發(fā)送的信息都經(jīng)過(guò)了websocket服務(wù),里面可以做差異化處理哦。要存儲發(fā)送記錄,記錄是否消費,后面再通過(guò)自動(dòng)任務(wù)掃描這種未被消費(發(fā)送失?。┑男畔?,等用戶(hù)上線(xiàn)再次發(fā)送,實(shí)現推送信息等等。
到此這篇關(guān)于springboot簡(jiǎn)單接入websocket的方法的文章就介紹到這了,更多相關(guān)springboot接入websocket內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站