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):負(fù)責(zé)業(yè)務(wù)邏輯處理、WebSocket 消息分發(fā)和管理連接會話。
- 客戶端(Vue3):負(fù)責(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)文章
vue axios 給生產(chǎn)環(huán)境和發(fā)布環(huán)境配置不同的接口地址(推薦)
這篇文章主要介紹了vue axios 給生產(chǎn)環(huán)境和發(fā)布環(huán)境配置不同的接口地址,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2018-05-05
Vue中render函數(shù)調(diào)用時機與執(zhí)行細(xì)節(jié)源碼分析
這篇文章主要為大家介紹了Vue中render函數(shù)調(diào)用時機與執(zhí)行細(xì)節(jié)源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
Vue.js組件tree實現(xiàn)省市多級聯(lián)動
這篇文章主要為大家詳細(xì)介紹了Vue.js組件tree實現(xiàn)省市多級聯(lián)動的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
Vue ElementUI實現(xiàn):限制輸入框只能輸入正整數(shù)的問題

