Vue3結(jié)合SpringBoot打造一個(gè)高效Web實(shí)時(shí)消息推送系統(tǒng)
在傳統(tǒng)的 HTTP 通信模型中,客戶端想要獲取最新數(shù)據(jù),必須不斷地向服務(wù)器發(fā)送請求進(jìn)行詢問——這種方式稱為輪詢。
假設(shè)你正在訪問一個(gè)股票信息平臺,瀏覽器每隔數(shù)秒就向服務(wù)器發(fā)送請求,服務(wù)器回復(fù):“暫時(shí)沒變化”,直到股價(jià)真正變化為止。這不僅浪費(fèi)帶寬,也帶來了數(shù)據(jù)更新的延遲。
而 WebSocket 則從根本上改變了這個(gè)機(jī)制。它在客戶端與服務(wù)器之間建立一條持久連接,允許服務(wù)端主動將新消息推送給客戶端。這就像雙方之間開了一個(gè)微信語音通話頻道,消息來回即時(shí)互通,無需每次“掛斷再撥號”。
典型應(yīng)用場景:
- 實(shí)時(shí)聊天(如微信、釘釘)
- 股票/幣價(jià)推送
- 實(shí)時(shí)協(xié)作文檔編輯
- 在線訂單通知/預(yù)警系統(tǒng)
系統(tǒng)構(gòu)建:技術(shù)選型與項(xiàng)目結(jié)構(gòu)
為了實(shí)現(xiàn)一個(gè)具有實(shí)時(shí)消息推送能力的 Web 應(yīng)用,我們采用如下架構(gòu):
- 服務(wù)端(Spring Boot):負(fù)責(zé)業(yè)務(wù)邏輯處理、WebSocket 消息分發(fā)和管理連接會話。
- 客戶端(Vue3):負(fù)責(zé) UI 展示和 WebSocket 的消息接收/顯示。
Spring Boot 服務(wù)端實(shí)現(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 前端實(shí)現(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>部署上線實(shí)戰(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)機(jī)制
服務(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é)
通過本項(xiàng)目的實(shí)戰(zhàn)與優(yōu)化,我們打造了一個(gè)功能完整的實(shí)時(shí)消息推送系統(tǒng),它具備如下特性:
- 前后端解耦,通信基于 WebSocket + STOMP
- 消息反應(yīng)秒級可達(dá)
- 支持鑒權(quán),可與登陸系統(tǒng)完編合
- 具備斷線重連能力
- 可實(shí)際部署,用 Nginx 做網(wǎng)關(guān)分發(fā)
到此這篇關(guān)于Vue3結(jié)合SpringBoot打造一個(gè)高效Web實(shí)時(shí)消息推送系統(tǒng)的文章就介紹到這了,更多相關(guān)Vue3 SpringBoot消息推送內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 基于Vue3和SpringBoot實(shí)現(xiàn)Web實(shí)時(shí)消息推送功能
- websocket實(shí)現(xiàn)Vue?3和Node.js之間的實(shí)時(shí)消息推送
- vue使用stompjs實(shí)現(xiàn)mqtt消息推送通知
- SpringBoot實(shí)現(xiàn)網(wǎng)頁消息推送的5種方法小結(jié)
- SpringBoot+WebSocket向前端推送消息的實(shí)現(xiàn)示例
- springboot整合mqtt實(shí)現(xiàn)消息訂閱和推送功能
- Springboot Websocket Stomp 消息訂閱推送
相關(guān)文章
vue子組件中使用window.onresize()只執(zhí)行一次問題
這篇文章主要介紹了vue子組件中使用window.onresize()只執(zhí)行一次問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
vue項(xiàng)目打包上傳github并制作預(yù)覽鏈接(pages)
這篇文章主要介紹了vue項(xiàng)目打包上傳github并制作預(yù)覽鏈接(pages)的相關(guān)資料,需要的朋友可以參考下2019-04-04
vue中v-if和v-for一起使用的弊端及解決辦法(同時(shí)使用 v-if 和 v-for不
當(dāng) v-if 和 v-for 同時(shí)存在于一個(gè)元素上的時(shí)候,v-if 會首先被執(zhí)行,這篇文章主要介紹了vue中v-if和v-for一起使用的弊端及解決辦法,需要的朋友可以參考下2023-07-07
Vue3 去除 vue warn 及生產(chǎn)環(huán)境去除console.log的方法
這篇文章主要介紹了Vue3 去除 vue warn 及生產(chǎn)環(huán)境去除console.log的方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
vue從后臺渲染文章列表以及根據(jù)id跳轉(zhuǎn)文章詳情詳解
這篇文章主要給大家介紹了關(guān)于vue從后臺渲染文章列表以及根據(jù)id跳轉(zhuǎn)文章詳情的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Vue3中使用Element-Plus的el-upload組件限制只上傳一個(gè)文件的功能實(shí)現(xiàn)
在 Vue 3 中使用 Element-Plus 的 el-upload 組件進(jìn)行文件上傳時(shí),有時(shí)候需要限制只能上傳一個(gè)文件,本文將介紹如何通過配置 el-upload 組件實(shí)現(xiàn)這個(gè)功能,讓你的文件上傳變得更加簡潔和易用,需要的朋友可以參考下2023-10-10

