springboot簡單接入websocket的操作方法
序
最近一個項目又重啟了,之前支付了要手動點擊已付款,所以這次想把這個不友好體驗干掉。另外以后的掃碼登錄什么的都需要這個服務支持。之前掃碼登錄這塊用的mqtt,時間上是直接把mqtt的連接信息返回給前端。前端連接mqtt服務,消費信息。這次不想這樣弄了,準備接入websocket。
一、環(huán)境說明
我這里是springBoot2.4.5 + springCloud2020.1.2,這里先從springBoot對接開始,逐步再增加深度,不過可能時間不夠,就簡單接入能滿足現(xiàn)在業(yè)務場景就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)變量,用來記錄當前在線連接數(shù)。應該把它設計成線程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的線程安全Set,用來存放每個客戶端對應的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 + ",當前在線人數(shù)為:" + getOnlineCount());
sendMessage("連接成功");
}
/**
* 連接關閉
* 調(diào)用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(wsUserId)) {
webSocketMap.remove(wsUserId);
//從set中刪除
subOnlineCount();
}
log.info("用戶退出:" + wsUserId + ",當前在線人數(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");
//傳送給對應toUserId用戶的websocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(message);
} else {
//否則不在這個服務器上,發(fā)送到mysql或者redis
log.error("請求的userId:" + toUserId + "不在該服務器上");
}
} 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();
}
}
核心方法就這么幾個,這里面的細節(jié)可以自行根據(jù)業(yè)務場景處理,比如給信息增加一個類型,然后搞個公用方法,根據(jù)信息類型走不同業(yè)務邏輯,存庫等等都可以的。
五、前端測試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)消息進入,開始處理前端觸發(fā)邏輯
};
//關閉事件
socket.onclose = function() {
console.log("websocket已關閉");
};
//發(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>【客戶端向服務器發(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>【關閉連接】:<div><a onclick="closeSocket()">關閉socket</a></div>
</body>
</html>
六、測試效果

到此就結(jié)束了,基本上就是這么簡單,我這邊發(fā)送,另一個網(wǎng)頁上能收到,而且發(fā)送的信息都經(jīng)過了websocket服務,里面可以做差異化處理哦。要存儲發(fā)送記錄,記錄是否消費,后面再通過自動任務掃描這種未被消費(發(fā)送失?。┑男畔?,等用戶上線再次發(fā)送,實現(xiàn)推送信息等等。
到此這篇關于springboot簡單接入websocket的方法的文章就介紹到這了,更多相關springboot接入websocket內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于springboot+vue實現(xiàn)垃圾分類管理系統(tǒng)
這篇文章主要為大家詳細介紹了基于springboot+vue實現(xiàn)垃圾分類管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07
Spring容器刷新obtainFreshBeanFactory示例詳解
這篇文章主要為大家介紹了Spring容器刷新obtainFreshBeanFactory示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
Java中this和super的區(qū)別及this能否調(diào)用到父類使用
這篇文章主要介紹了Java中this和super的區(qū)別及this能否調(diào)用到父類使用,this和super都是Java中常見的關鍵字,下文關于兩者區(qū)別介紹,需要的小伙伴可以參考一下2022-05-05
Java編程實現(xiàn)五子棋人人對戰(zhàn)代碼示例
這篇文章主要介紹了Java編程實現(xiàn)五子棋人人對戰(zhàn)代碼示例,具有一定借鑒價值,需要的朋友可以參考下。2017-11-11

