基于Vue3和SpringBoot實(shí)現(xiàn)Web實(shí)時(shí)消息推送功能
前言
先看演示效果:后端發(fā)送消息,前端實(shí)時(shí)展示

1. WebSocket
WebSocket 是一種常用的實(shí)現(xiàn) web 實(shí)時(shí)消息推送的技術(shù)。

我們先看**傳統(tǒng)網(wǎng)站(HTTP)**的缺點(diǎn):
假設(shè)你打開一個(gè)股票網(wǎng)站,網(wǎng)頁會(huì)反復(fù)問服務(wù)器:“股價(jià)變了嗎?”(刷新請求) → 服務(wù)器:“沒變”(響應(yīng))... 過2秒網(wǎng)頁又問:“變了嗎?”... 服務(wù)器:“漲了!”
這就像你每隔2秒就打電話問朋友:“有消息嗎?” —— 效率低、費(fèi)流量、延遲高。
WebSocket 是什么?
可以理解為你和服務(wù)器開了一個(gè)“專線通話”:
首次連接時(shí),用HTTP協(xié)議握手(打個(gè)招呼建立連接)
連接保持不中斷,服務(wù)器可以隨時(shí)主動(dòng)給你發(fā)消息,你也能隨時(shí)發(fā)消息給服務(wù)器
實(shí)時(shí)雙向通信,不再需要反復(fù)問“有消息嗎?”
就像你和朋友微信語音通話,接通后雙方隨時(shí)都能說話,不用掛斷重?fù)堋?/p>
實(shí)際場景:
聊天軟件(微信、釘釘):消息秒達(dá),不用刷新頁面
股票實(shí)時(shí)行情:股價(jià)變動(dòng)立即推送到你屏幕
協(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();
});
前端頁面顯示連接成功

以上就是基于Vue3和SpringBoot實(shí)現(xiàn)Web實(shí)時(shí)消息推送功能的詳細(xì)內(nèi)容,更多關(guān)于Vue3 SpringBoot Web消息推送的資料請關(guān)注腳本之家其它相關(guān)文章!
- 利用Vue3?+?SpringBoot打造高效Web實(shí)時(shí)消息推送系統(tǒng)
- Vue3結(jié)合SpringBoot打造一個(gè)高效Web實(shí)時(shí)消息推送系統(tǒng)
- SpringBoot整合SSE接口實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)推送
- SpringBoot+SseEmitter和Vue3+EventSource實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)推送
- SpringBoot集成WebSocket【基于純H5】進(jìn)行點(diǎn)對點(diǎn)[一對一]和廣播[一對多]實(shí)時(shí)推送
- SpringBoot+ResponseBodyEmitter實(shí)時(shí)異步流式推送的實(shí)現(xiàn)
相關(guān)文章
基于uniapp+vue3?實(shí)現(xiàn)72小時(shí)倒計(jì)時(shí)功能
數(shù)組項(xiàng)有一個(gè)下單時(shí)間?,比如今天下單在72小時(shí)內(nèi)可以繼續(xù)支付,超過則默認(rèn)取消訂單,下面通過實(shí)例代碼介紹uniapp+vue3?實(shí)現(xiàn)72小時(shí)倒計(jì)時(shí)功能,感興趣的朋友一起看看吧2025-05-05
解決vue-element-admin安裝依賴npm install報(bào)錯(cuò)問題
這篇文章主要介紹了解決vue-element-admin安裝依賴npm install報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
Vue3實(shí)現(xiàn)word轉(zhuǎn)成pdf代碼的方法
在Vue 3中,前端無法直接將Word文檔轉(zhuǎn)換為PDF,因?yàn)閃ord文檔的解析和PDF的生成通常需要在后端進(jìn)行這篇文章主要介紹了Vue3實(shí)現(xiàn)word轉(zhuǎn)成pdf代碼的方法,需要的朋友可以參考下,2023-07-07
vue實(shí)現(xiàn)商城秒殺倒計(jì)時(shí)功能
這篇文章主要介紹了vue實(shí)現(xiàn)商城秒殺倒計(jì)時(shí)功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
Vue 項(xiàng)目中遇到的跨域問題及解決方法(后臺(tái)php)
這篇文章主要介紹了Vue 項(xiàng)目中遇到的跨域問題及解決方法(后臺(tái)php),前端采用vue框架,后臺(tái)php,具體解決方法,大家參考下本文2018-03-03
基于vue v-for 多層循環(huán)嵌套獲取行數(shù)的方法
今天小編就為大家分享一篇基于vue v-for 多層循環(huán)嵌套獲取行數(shù)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

