Vue3結(jié)合SpringBoot打造一個高效Web實時消息推送系統(tǒng)
在傳統(tǒng)的 HTTP 通信模型中,客戶端想要獲取最新數(shù)據(jù),必須不斷地向服務(wù)器發(fā)送請求進行詢問——這種方式稱為輪詢。
假設(shè)你正在訪問一個股票信息平臺,瀏覽器每隔數(shù)秒就向服務(wù)器發(fā)送請求,服務(wù)器回復(fù):“暫時沒變化”,直到股價真正變化為止。這不僅浪費帶寬,也帶來了數(shù)據(jù)更新的延遲。
而 WebSocket 則從根本上改變了這個機制。它在客戶端與服務(wù)器之間建立一條持久連接,允許服務(wù)端主動將新消息推送給客戶端。這就像雙方之間開了一個微信語音通話頻道,消息來回即時互通,無需每次“掛斷再撥號”。
典型應(yīng)用場景:
- 實時聊天(如微信、釘釘)
- 股票/幣價推送
- 實時協(xié)作文檔編輯
- 在線訂單通知/預(yù)警系統(tǒng)
系統(tǒng)構(gòu)建:技術(shù)選型與項目結(jié)構(gòu)
為了實現(xiàn)一個具有實時消息推送能力的 Web 應(yīng)用,我們采用如下架構(gòu):
- 服務(wù)端(Spring Boot):負責(zé)業(yè)務(wù)邏輯處理、WebSocket 消息分發(fā)和管理連接會話。
- 客戶端(Vue3):負責(zé) UI 展示和 WebSocket 的消息接收/顯示。
Spring Boot 服務(wù)端實現(xiàn)
Maven 依賴
<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");
registry.setApplicationDestinationPrefixes("/app");
}
}
消息推送服務(wù)
@Service
public class NotificationService {
@Autowired
private SimpMessagingTemplate messagingTemplate;
public void broadcastNewOrder(String orderNumber) {
messagingTemplate.convertAndSend("/topic/new-orders", orderNumber);
}
public void notifyUser(String userId, String message) {
messagingTemplate.convertAndSendToUser(userId, "/topic/notification", message);
}
}
Vue3 前端實現(xiàn)
安裝依賴
npm install sockjs-client stompjs
/utils/websocket.js
import SockJS from 'sockjs-client/dist/sockjs';
import Stomp from 'stompjs';
let stompClient = null;
let retryInterval = 5000;
let reconnectTimer = null;
function scheduleReconnect(type, notifyCallback, refreshCallback) {
reconnectTimer = setTimeout(() => {
connectWebSocket(type, notifyCallback, refreshCallback);
}, retryInterval);
}
export function connectWebSocket(type, notifyCallback, refreshCallback) {
const socket = new SockJS(import.meta.env.VITE_WS_ENDPOINT || "http://localhost:8083/ws-notification");
stompClient = Stomp.over(socket);
stompClient.connect({}, () => {
if (reconnectTimer) clearTimeout(reconnectTimer);
stompClient.subscribe(`/topic/${type}`, (msg) => {
notifyCallback(msg.body);
refreshCallback?.();
});
}, (error) => {
console.error("連接失敗,嘗試重連", error);
scheduleReconnect(type, notifyCallback, refreshCallback);
});
}
export function disconnectWebSocket() {
if (stompClient) {
stompClient.disconnect();
}
}
Vue 組件使用
<script setup>
import { onMounted, onBeforeUnmount } from "vue";
import { ElNotification } from "element-plus";
import { connectWebSocket, disconnectWebSocket } from "@/utils/websocket";
const showNotification = (message) => {
ElNotification({
title: "新訂單提醒",
type: "success",
message: message,
});
};
onMounted(() => {
connectWebSocket("new-orders", showNotification, refreshOrderList);
});
onBeforeUnmount(() => {
disconnectWebSocket();
});
function refreshOrderList() {
console.log("刷新訂單列表");
}
</script>部署上線實戰(zhàn)
Nginx 配置 WebSocket 中繼
location /ws-notification {
proxy_pass http://localhost:8083/ws-notification;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
Vue 打包和環(huán)境變量
const socket = new SockJS(import.meta.env.VITE_WS_ENDPOINT || "http://localhost:8083/ws-notification");
WebSocket 鑒權(quán)機制
服務(wù)端 STOMP 攔截器
@Component
public class AuthChannelInterceptor implements ChannelInterceptor {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authHeaders = accessor.getNativeHeader("Authorization");
String token = (authHeaders != null && !authHeaders.isEmpty()) ? authHeaders.get(0) : null;
if (!TokenUtil.verify(token)) {
throw new IllegalArgumentException("無效的 Token");
}
accessor.setUser(new UsernamePasswordAuthenticationToken("user", null, new ArrayList<>()));
}
return message;
}
}
在 WebSocket 配置中注冊
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new AuthChannelInterceptor());
}
客戶端使用 Token
stompClient.connect({ Authorization: getToken() }, () => {
stompClient.subscribe("/topic/new-orders", (msg) => {
notifyCallback(msg.body);
});
});
總結(jié)
通過本項目的實戰(zhàn)與優(yōu)化,我們打造了一個功能完整的實時消息推送系統(tǒng),它具備如下特性:
- 前后端解耦,通信基于 WebSocket + STOMP
- 消息反應(yīng)秒級可達
- 支持鑒權(quán),可與登陸系統(tǒng)完編合
- 具備斷線重連能力
- 可實際部署,用 Nginx 做網(wǎng)關(guān)分發(fā)
到此這篇關(guān)于Vue3結(jié)合SpringBoot打造一個高效Web實時消息推送系統(tǒng)的文章就介紹到這了,更多相關(guān)Vue3 SpringBoot消息推送內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VUE2—defineProperty和VUE3—proxy使用方式
Vue2和Vue3的響應(yīng)式原理不同,Vue2使用Object.defineProperty,Vue3使用Proxy,Object.defineProperty可以監(jiān)聽某個屬性,但不能監(jiān)聽整個對象,且無法監(jiān)聽對象屬性的新增和刪除,Proxy可以監(jiān)聽整個對象,且不會修改原數(shù)據(jù),可以監(jiān)聽數(shù)組的長度變化2025-01-01
Vue+element 日期時間組件選擇器精確到分鐘禁止選秒的配置方法
文章介紹如何在Vue+Element UI中配置日期時間選擇器精確到分鐘并禁用秒選擇,通過設(shè)置顯示格式和樣式實現(xiàn),同時提供相關(guān)擴展內(nèi)容參考,感興趣的朋友一起看看吧2025-07-07
vue2.0/3.0的響應(yīng)式原理及區(qū)別淺析
這篇文章主要給大家介紹了關(guān)于vue2.0/3.0響應(yīng)式原理及區(qū)別的相關(guān)資料,文中通過圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

