springboot簡單接入websocket的操作方法
序
最近一個項目又重啟了,之前支付了要手動點(diǎn)擊已付款,所以這次想把這個不友好體驗(yàn)干掉。另外以后的掃碼登錄什么的都需要這個服務(wù)支持。之前掃碼登錄這塊用的mqtt,時間上是直接把mqtt的連接信息返回給前端。前端連接mqtt服務(wù),消費(fèi)信息。這次不想這樣弄了,準(zhǔn)備接入websocket。
一、環(huán)境說明
我這里是springBoot2.4.5 + springCloud2020.1.2,這里先從springBoot對接開始,逐步再增加深度,不過可能時間不夠,就簡單接入能滿足現(xiàn)在業(yè)務(wù)場景就stop。沒辦法,從入職就開始的一個項目到現(xiàn)在,要死不活的,沒有客戶就不投入,有客戶就催命,真不知道還能堅持多久。。。。。。
二、引包
<!-- websocket支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
現(xiàn)在springboot對接websocket就值需要這么簡單的一個包了。
三、配置類
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();
}
}
就這一個,里面的bean是用來掃描Endpoint注解的類的。
配置文件都沒什么好說的,簡單對接用不上,也不用什么調(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è)計成線程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的WebSocket對象。
*/
private static ConcurrentHashMap<String, MyWebSocketSever> webSocketMap = new ConcurrentHashMap<>();
/**
* 與某個客戶端的連接會話,需要通過它來給客戶端發(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 + ",報文:" + message);
//可以群發(fā)消息
//消息保存到數(shù)據(jù)庫、redis
if (StringUtils.isNotBlank(message)) {
try {
//解析發(fā)送的報文
JSONObject jsonObject = JSON.parseObject(message);
//追加發(fā)送人(防止串改)
jsonObject.put("fromUserId", this.wsUserId);
String toUserId = jsonObject.getString("toUserId");
//傳送給對應(yīng)toUserId用戶的websocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(message);
} else {
//否則不在這個服務(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("用戶錯誤:" + this.wsUserId + ",原因:" + error.getMessage());
error.printStackTrace();
}
}
核心方法就這么幾個,這里面的細(xì)節(jié)可以自行根據(jù)業(yè)務(wù)場景處理,比如給信息增加一個類型,然后搞個公用方法,根據(jù)信息類型走不同業(yè)務(wù)邏輯,存庫等等都可以的。
五、前端測試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ā)生了錯誤事件
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開啟者的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>
六、測試效果

到此就結(jié)束了,基本上就是這么簡單,我這邊發(fā)送,另一個網(wǎng)頁上能收到,而且發(fā)送的信息都經(jīng)過了websocket服務(wù),里面可以做差異化處理哦。要存儲發(fā)送記錄,記錄是否消費(fèi),后面再通過自動任務(wù)掃描這種未被消費(fèi)(發(fā)送失敗)的信息,等用戶上線再次發(fā)送,實(shí)現(xiàn)推送信息等等。
到此這篇關(guān)于springboot簡單接入websocket的方法的文章就介紹到這了,更多相關(guān)springboot接入websocket內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot集成WebSocket長連接實(shí)際應(yīng)用詳解
- SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的示例代碼
- springboot websocket集群(stomp協(xié)議)連接時候傳遞參數(shù)
- springboot websocket簡單入門示例
- SpringBoot+Websocket實(shí)現(xiàn)一個簡單的網(wǎng)頁聊天功能代碼
- Spring Boot 開發(fā)私有即時通信系統(tǒng)(WebSocket)
- SpringBoot webSocket實(shí)現(xiàn)發(fā)送廣播、點(diǎn)對點(diǎn)消息和Android接收
相關(guān)文章
JavaScript中HTML元素操作的實(shí)現(xiàn)
本文主要介紹了JavaScript中HTML元素操作的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Java的ConcurrentLinkedQueue源碼分析
這篇文章主要介紹了Java的ConcurrentLinkedQueue源碼分析,ConcurrentLinkedQueue 是一個基于鏈接節(jié)點(diǎn)的無界線程安全的隊列,當(dāng)我們添加一個元素的時候,它會添加到隊列的尾部,當(dāng)我們獲取一個元素時,它會返回隊列頭部的元素,需要的朋友可以參考下2023-12-12
Spring Data JPA實(shí)現(xiàn)排序與分頁查詢超詳細(xì)流程講解
在介紹Spring Data JPA的時候,我們首先認(rèn)識下Hibernate。Hibernate是數(shù)據(jù)訪問解決技術(shù)的絕對霸主,使用O/R映射技術(shù)實(shí)現(xiàn)數(shù)據(jù)訪問,O/R映射即將領(lǐng)域模型類和數(shù)據(jù)庫的表進(jìn)行映射,通過程序操作對象而實(shí)現(xiàn)表數(shù)據(jù)操作的能力,讓數(shù)據(jù)訪問操作無須關(guān)注數(shù)據(jù)庫相關(guān)的技術(shù)2022-10-10

