1.前言
先看演示效果:后端發(fā)送消息,前端實(shí)時(shí)展示

1.1 WebSocket
WebSocket 是一種常用的實(shí)現(xiàn) web 實(shí)時(shí)消息推送的技術(shù)。
我們先看傳統(tǒng)網(wǎng)站(HTTP)的缺點(diǎn):
假設(shè)你打開一個股票網(wǎng)站,網(wǎng)頁會反復(fù)問服務(wù)器:“股價(jià)變了嗎?”(刷新請求) → 服務(wù)器:“沒變”(響應(yīng))... 過2秒網(wǎng)頁又問:“變了嗎?”... 服務(wù)器:“漲了!”
這就像你每隔2秒就打電話問朋友:“有消息嗎?” —— 效率低、費(fèi)流量、延遲高。
WebSocket 是什么?
可以理解為你和服務(wù)器開了一個“專線通話”:
首次連接時(shí),用HTTP協(xié)議握手(打個招呼建立連接)
連接保持不中斷,服務(wù)器可以隨時(shí)主動給你發(fā)消息,你也能隨時(shí)發(fā)消息給服務(wù)器
實(shí)時(shí)雙向通信,不再需要反復(fù)問“有消息嗎?”
就像你和朋友微信語音通話,接通后雙方隨時(shí)都能說話,不用掛斷重?fù)堋?/span>
實(shí)際場景:
聊天軟件(微信、釘釘):消息秒達(dá),不用刷新頁面
股票實(shí)時(shí)行情:股價(jià)變動立即推送到你屏幕
協(xié)同編輯(如騰訊文檔):多人編輯時(shí)內(nèi)容實(shí)時(shí)同步
2. 環(huán)境搭建
在 Spring Boot 與 Vue 整合 WebSocket 消息通知的場景中,通常Spring Boot 項(xiàng)目作為服務(wù)端,而 Vue 項(xiàng)目作為客戶端。這種架構(gòu)設(shè)計(jì)的原因如下:
Spring Boot(服務(wù)端):負(fù)責(zé)消息處理、業(yè)務(wù)邏輯、數(shù)據(jù)持久化,以及與 WebSocket 客戶端的連接管理。
Vue(客戶端):通過瀏覽器提供用戶界面,并使用 JavaScript 的 WebSocket API 連接到服務(wù)端,接收和展示消息。
2.1 Vue 項(xiàng)目
在 Vue 項(xiàng)目中,我們使用 sockjs-client 和 stomp.js 庫來連接 WebSocket。
npm install sockjs-client stompjs
創(chuàng)建 websocket.js
import SockJS from "sockjs-client/dist/sockjs";
import Stomp from "stompjs";
let stompClient = null;
// 連接
export function connectWebSocket(type, notifyCallback, listRefreshCallback) {
const socket = new SockJS("http://localhost:8083/zhifou-blog/ws-notification");
stompClient = Stomp.over(socket);
stompClient.connect({}, () => {
// 訂閱新訂單
if (type === "new-orders") {
stompClient.subscribe("/topic/new-orders", (message) => {
notifyCallback(message.body);
listRefreshCallback();
});
}
if (type === "return-orders") {
// 訂閱退單
stompClient.subscribe("/topic/return-orders", (message) => {
notifyCallback(message.body);
listRefreshCallback();
});
}
});
}
// 關(guān)閉連接
export function disconnectWebSocket() {
if (stompClient !== null) {
stompClient.disconnect();
}
}
2.2 SpringBoot 項(xiàng)目
添加依賴
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocket 配置類
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-notification")
.setAllowedOriginPatterns("*")// 允許跨域
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 客戶端訂閱路徑前綴
registry.enableSimpleBroker("/topic");
// 客戶端發(fā)送消息的路徑前綴
registry.setApplicationDestinationPrefixes("/app");
}
}
3. 核心代碼
3.1 后端
// 注入依賴
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
// 發(fā)送消息
simpMessagingTemplate.convertAndSend("/topic/new-orders"",orderNumber);
// 向特定客戶發(fā)送消息
simpMessagingTemplate.convertAndSendToUser(userId, "/topic/notification", notification);
3.2 前端
import { onMounted, onBeforeUnmount, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { connectWebSocket, disconnectWebSocket } from "../../../utils/websocket";
// Dom 掛載之后
onMounted(() => {
// websocket鏈接
connectWebSocket(
"new-orders",
(message) => {
showNotification(message);
},
getOrderList
);
});
// showNotification
const showNotification = (message) => {
ElNotification({
title: "新的訂單",
type: "success",
message: message,
});
};
onBeforeUnmount(() => {
disconnectWebSocket();
});
前端頁面顯示連接成功
閱讀原文:原文鏈接
該文章在 2025/5/26 11:07:15 編輯過