springboot簡單接入websocket的操作方法
序
最近一個(gè)項(xiàng)目又重啟了,之前支付了要手動(dòng)點(diǎn)擊已付款,所以這次想把這個(gè)不友好體驗(yàn)干掉。另外以后的掃碼登錄什么的都需要這個(gè)服務(wù)支持。之前掃碼登錄這塊用的mqtt,時(shí)間上是直接把mqtt的連接信息返回給前端。前端連接mqtt服務(wù),消費(fèi)信息。這次不想這樣弄了,準(zhǔn)備接入websocket。
一、環(huán)境說明
我這里是springBoot2.4.5 + springCloud2020.1.2,這里先從springBoot對(duì)接開始,逐步再增加深度,不過可能時(shí)間不夠,就簡單接入能滿足現(xiàn)在業(yè)務(wù)場景就stop。沒辦法,從入職就開始的一個(gè)項(xiàng)目到現(xiàn)在,要死不活的,沒有客戶就不投入,有客戶就催命,真不知道還能堅(jiān)持多久。。。。。。
二、引包
<!-- websocket支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
現(xiàn)在springboot對(duì)接websocket就值需要這么簡單的一個(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配置類 * * @author zhengwen **/ @Slf4j @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
就這一個(gè),里面的bean是用來掃描Endpoint注解的類的。
配置文件都沒什么好說的,簡單對(duì)接用不上,也不用什么調(diào)優(yōu)。
四、websocketServer
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)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。 */ private static int onlineCount = 0; /** * concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的WebSocket對(duì)象。 */ private static ConcurrentHashMap<String, MyWebSocketSever> webSocketMap = new ConcurrentHashMap<>(); /** * 與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù) */ private Session session; /** * 接收wsUserId */ private String wsUserId = ""; /** * 連接建立成 * 功調(diào)用的方法 */ @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); //在線數(shù)加1 addOnlineCount(); } log.info("用戶連接:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount()); sendMessage("連接成功"); } /** * 連接關(guān)閉 * 調(diào)用的方法 */ @OnClose public void onClose() { if (webSocketMap.containsKey(wsUserId)) { webSocketMap.remove(wsUserId); //從set中刪除 subOnlineCount(); } log.info("用戶退出:" + wsUserId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount()); } /** * 收到客戶端消 * 息后調(diào)用的方法 * * @param message 客戶端發(fā)送過來的消息 **/ @OnMessage public void onMessage(String message, Session session) { log.info("用戶消息:" + wsUserId + ",報(bào)文:" + message); //可以群發(fā)消息 //消息保存到數(shù)據(jù)庫、redis if (StringUtils.isNotBlank(message)) { try { //解析發(fā)送的報(bào)文 JSONObject jsonObject = JSON.parseObject(message); //追加發(fā)送人(防止串改) jsonObject.put("fromUserId", this.wsUserId); String toUserId = jsonObject.getString("toUserId"); //傳送給對(duì)應(yīng)toUserId用戶的websocket if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) { webSocketMap.get(toUserId).sendMessage(message); } else { //否則不在這個(gè)服務(wù)器上,發(fā)送到mysql或者redis log.error("請(qǐng)求的userId:" + toUserId + "不在該服務(wù)器上"); } } catch (Exception e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用戶錯(cuò)誤:" + this.wsUserId + ",原因:" + error.getMessage()); error.printStackTrace(); } }
核心方法就這么幾個(gè),這里面的細(xì)節(jié)可以自行根據(jù)業(yè)務(wù)場景處理,比如給信息增加一個(gè)類型,然后搞個(gè)公用方法,根據(jù)信息類型走不同業(yè)務(wù)邏輯,存庫等等都可以的。
五、前端測(cè)試js
<!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); //打開事件 socket.onopen = function() { console.log("websocket已打開"); }; //獲得消息事件 socket.onmessage = function(msg) { console.log(msg.data); //發(fā)現(xiàn)消息進(jìn)入,開始處理前端觸發(fā)邏輯 }; //關(guān)閉事件 socket.onclose = function() { console.log("websocket已關(guān)閉"); }; //發(fā)生了錯(cuò)誤事件 socket.onerror = function() { console.log("websocket發(fā)生了錯(cuò)誤"); } } 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開啟者的ID信息】:<div><input id="userId" name="userId" type="text" value="10"></div> <p>【客戶端向服務(wù)器發(fā)送的內(nèi)容】:<div><input id="toUserId" name="toUserId" type="text" value="20"> <input id="contentText" name="contentText" type="text" value="hello websocket"></div> <p>【開啟連接】:<div><a onclick="openSocket()">開啟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>
六、測(cè)試效果
到此就結(jié)束了,基本上就是這么簡單,我這邊發(fā)送,另一個(gè)網(wǎng)頁上能收到,而且發(fā)送的信息都經(jīng)過了websocket服務(wù),里面可以做差異化處理哦。要存儲(chǔ)發(fā)送記錄,記錄是否消費(fèi),后面再通過自動(dòng)任務(wù)掃描這種未被消費(fèi)(發(fā)送失敗)的信息,等用戶上線再次發(fā)送,實(shí)現(xiàn)推送信息等等。
到此這篇關(guān)于springboot簡單接入websocket的方法的文章就介紹到這了,更多相關(guān)springboot接入websocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成WebSocket長連接實(shí)際應(yīng)用詳解
- SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的示例代碼
- springboot websocket集群(stomp協(xié)議)連接時(shí)候傳遞參數(shù)
- springboot websocket簡單入門示例
- SpringBoot+Websocket實(shí)現(xiàn)一個(gè)簡單的網(wǎng)頁聊天功能代碼
- Spring Boot 開發(fā)私有即時(shí)通信系統(tǒng)(WebSocket)
- SpringBoot webSocket實(shí)現(xiàn)發(fā)送廣播、點(diǎn)對(duì)點(diǎn)消息和Android接收
相關(guān)文章
Eclipse將Maven項(xiàng)目打成jar包的方法
這篇文章主要介紹了Eclipse將Maven項(xiàng)目打成jar包的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2007-09-09基于springboot+vue實(shí)現(xiàn)垃圾分類管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于springboot+vue實(shí)現(xiàn)垃圾分類管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07Spring容器刷新obtainFreshBeanFactory示例詳解
這篇文章主要為大家介紹了Spring容器刷新obtainFreshBeanFactory示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Java中this和super的區(qū)別及this能否調(diào)用到父類使用
這篇文章主要介紹了Java中this和super的區(qū)別及this能否調(diào)用到父類使用,this和super都是Java中常見的關(guān)鍵字,下文關(guān)于兩者區(qū)別介紹,需要的小伙伴可以參考一下2022-05-05Java編程實(shí)現(xiàn)五子棋人人對(duì)戰(zhàn)代碼示例
這篇文章主要介紹了Java編程實(shí)現(xiàn)五子棋人人對(duì)戰(zhàn)代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-11-11使用 Java8 實(shí)現(xiàn)觀察者模式的方法(下)
這篇文章主要介紹了使用 Java8 實(shí)現(xiàn)觀察者模式的方法(下)的相關(guān)資料,需要的朋友可以參考下2016-02-02