實戰突破!Vue3 + SpringBoot 打造高效 Web 實時消息推送系統
為何需要 Web 實時通信?
在傳統的 HTTP 通信模型中,客戶端想要獲取最新數據,必須不斷地向服務器發送請求進行詢問——這種方式稱為輪詢。
假設你正在訪問一個股票信息平臺,瀏覽器每隔數秒就向服務器發送請求,服務器回復:“暫時沒變化”,直到股價真正變化為止。這不僅浪費帶寬,也帶來了數據更新的延遲。
而 WebSocket 則從根本上改變了這個機制。它在客戶端與服務器之間建立一條持久連接,允許服務端主動將新消息推送給客戶端。這就像雙方之間開了一個微信語音通話頻道,消息來回即時互通,無需每次“掛斷再撥號”。
典型應用場景:
- 實時聊天(如微信、釘釘)
- 股票/幣價推送
- 實時協作文檔編輯
- 在線訂單通知/預警系統
系統構建:技術選型與項目結構
為了實現一個具有實時消息推送能力的 Web 應用,我們采用如下架構:
- 服務端(Spring Boot):負責業務邏輯處理、WebSocket 消息分發和管理連接會話。
- 客戶端(Vue3):負責 UI 展示和 WebSocket 的消息接收/顯示。
Spring Boot 服務端實現
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");
}
}
消息推送服務
@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 前端實現
安裝依賴
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>
部署上線實戰
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 打包和環境變量
const socket = new SockJS(import.meta.env.VITE_WS_ENDPOINT || "http://localhost:8083/ws-notification");
WebSocket 鑒權機制
服務端 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);
});
});
總結:面向產品級的實時推送體系
通過本項目的實戰與優化,我們打造了一個功能完整的實時消息推送系統,它具備如下特性:
- 前后端解耦,通信基于 WebSocket + STOMP
- 消息反應秒級可達
- 支持鑒權,可與登陸系統完編合
- 具備斷線重連能力
- 可實際部署,用 Nginx 做網關分發