基于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)文章!
相關(guān)文章
使用vue自定義指令開發(fā)表單驗(yàn)證插件validate.js
今天就來介紹一下如何利用vue的自定義指令directive來開發(fā)一個(gè)表單驗(yàn)證插件的過程,需要的朋友可以參考下2019-05-05
詳解vuex之store拆分即多模塊狀態(tài)管理(modules)篇
這篇文章主要介紹了詳解vuex之store拆分即多模塊狀態(tài)管理(modules)篇,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11
Vue使用pinia管理數(shù)據(jù)pinia持久化存儲(chǔ)問題
這篇文章主要介紹了Vue使用pinia管理數(shù)據(jù)pinia持久化存儲(chǔ)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
vue2之jessibuca視頻插件使用教程詳細(xì)講解
Jessibuca進(jìn)行直播流播放,為用戶帶來便捷、高效的視頻觀看體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于vue2之jessibuca視頻插件使用的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-09-09
vue實(shí)現(xiàn)tab路由切換組件的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于vue實(shí)現(xiàn)tab路由切換組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
vue刷新頁面時(shí)去閃爍提升用戶體驗(yàn)效果的實(shí)現(xiàn)方法
這篇文章主要介紹了vue刷新頁面時(shí)去閃爍提升體驗(yàn)方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-12-12

