Springboot整合WebSocket實現訊息推送功能
阿新 • • 發佈:2021-06-25
專案結構
匯入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.3.7.RELEASE</spring-boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.72</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--websocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <!--工具包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.7.RELEASE</version> <configuration> <mainClass>com.example.demo.DemoApplication</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
application.yml配置檔案
server: port: 8080 spring: http: encoding:UTF-8 freemarker: request-context-attribute: request #prefix: /templates/ suffix: .html content-type: text/html enabled: true cache: false charset: UTF-8 allow-request-override: false expose-request-attributes: true expose-session-attributes: true expose-spring-macro-helpers: true
WebSocketConfig: 用於開啟WebSocket支援
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @author lyd * @Description: 開啟WebSocket支援 * @date 15:43 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
WebSocketServer: 核心類,用於開啟、關閉連線,以及接收訊息等
比較重要的註解 @ServerEndpoint("")
、@OnOpen
、@onClose
、@onMessage
package com.example.demo.server;
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 lyd
* @Description: 因為WebSocket是類似客戶端服務端的形式(採用ws協議),那麼這裡的WebSocketServer其實就相當於一個ws協議的Controller,
* 所以可以直接在前端呼叫@ServerEndpoint("")中的路徑,相當於掉介面了
* @date 15:48
*/
@Slf4j
@Component
@ServerEndpoint("/imserver/{userId}")
public class WebSocketServer {
/**
* 靜態變數,用來記錄當前線上連線數
*/
private static int onlineCount = 0;
/**
* Concurrent包的執行緒安全Set,用來存放每個客戶端對應的WebSocket物件
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 連線會話,給客戶端傳送資料
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
/**
* 連線建立成功呼叫的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
addOnlineCount();
} else {
webSocketMap.put(userId, this);
addOnlineCount();
}
log.info("使用者" + userId + "連線,當前線上人數為:" + getOnlineCount());
try {
sendMessage("連線成功");
} catch (IOException e) {
log.error("使用者:" + userId + ",網路異常,哈哈哈");
e.printStackTrace();
}
}
/**
* 連線關閉呼叫的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
subOnlineCount();
}
log.info("使用者:" + userId + "退出成功,當前線上人數為:" + getOnlineCount());
}
/**
* 收到客戶端訊息後呼叫的方法
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("使用者訊息:" + userId + ",報文:" + message);
//可以群發訊息
//訊息儲存到資料庫、redis
if (StringUtils.isNotBlank(message)) {
try {
// 解析報文
JSONObject jsonObject = JSON.parseObject(message);
// 追加發送人(防止串改)
jsonObject.put("fromUserId", this.userId);
String toUserId = jsonObject.getString("toUserId");
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
}else {
log.error("請求的userId:"+toUserId+"不在該伺服器上");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 實現伺服器訊息主動推送
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 傳送自定義訊息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
log.info("傳送訊息到:" + userId + ",報文:" + message);
if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("使用者" + userId + ",不線上!");
}
}
/**
* 獲得當前連線數
*
* @return
*/
public static synchronized int getOnlineCount() {
return onlineCount;
}
/**
* 線上連線數加1
*/
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
/**
* 線上連線數減1
*/
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("使用者錯誤:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
}
訊息推送
寫個controller介面呼叫WebSocketServer.sendInfo()
package com.example.demo.controller;
import com.example.demo.server.WebSocketServer;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.websocket.server.PathParam;
import java.io.IOException;
/**
* @author lyd
* @Description:
* @date 16:31
*/
@RestController
public class DemoController {
/**
* 介面測試
* @return
*/
@RequestMapping("index")
public ResponseEntity index(){
return ResponseEntity.ok("請求成功");
}
/**
* 頁面跳轉
* @return
*/
@RequestMapping("page")
public ModelAndView page(){
return new ModelAndView("testPage.html");
}
/**
* 訊息推送
* @param message
* @param toUserId
* @return
* @throws IOException
*/
@RequestMapping("pushToWeb")
public ResponseEntity<String> pushToWeb(String message, @PathParam("toUserId") String toUserId) throws IOException {
WebSocketServer.sendInfo(message,toUserId);
return ResponseEntity.ok("MSG SEND SUCCESS");
}
}
前端頁面程式碼
<!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>
var socket;
function openSocket() {
if (typeof (WebSocket) == "undefined") {
console.log("您的瀏覽器不支援WebSocket");
} else {
console.log("您的瀏覽器支援WebSocket");
//實現化WebSocket物件,指定要連線的伺服器地址與埠 建立連線
//等同於socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#userId").val();
var socketUrl = "http://localhost:8080/imserver/" + $("#userId").val();
socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
console.log(socketUrl);
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//開啟事件
socket.onopen = function () {
console.log("websocket已開啟");
//socket.send("這是來自客戶端的訊息" + location.href + new Date());
};
//獲得訊息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//發現訊息進入 開始處理前端觸發邏輯
};
//關閉事件
socket.onclose = function () {
console.log("websocket已關閉");
};
//發生了錯誤事件
socket.onerror = function () {
console.log("websocket發生了錯誤");
}
}
}
function sendMessage() {
if (typeof (WebSocket) == "undefined") {
console.log("您的瀏覽器不支援WebSocket");
} else {
console.log("您的瀏覽器支援WebSocket");
console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
}
}
</script>
<body>
<p>【userId】:
<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【toUserId】:
<div><input id="toUserId" name="toUserId" type="text" value="20"></div>
<p>【傳送內容】:
<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】:
<div><a onclick="openSocket()">開啟socket</a></div>
<p>【操作】:
<div><a onclick="sendMessage()">傳送訊息</a></div>
</body>
</html>
建立連線
傳送訊息
專案原始碼
https://github.com/Wranglery/test-websocket
感謝大佬的程式碼參考:https://blog.csdn.net/moshowgame/article/details/80275084