基于Vue3和SpringBoot實現(xiàn)Web實時消息推送功能
前言
先看演示效果:后端發(fā)送消息,前端實時展示
1. WebSocket
WebSocket 是一種常用的實現(xiàn) web 實時消息推送的技術。
我們先看**傳統(tǒng)網(wǎng)站(HTTP)**的缺點:
假設你打開一個股票網(wǎng)站,網(wǎng)頁會反復問服務器:“股價變了嗎?”(刷新請求) → 服務器:“沒變”(響應)... 過2秒網(wǎng)頁又問:“變了嗎?”... 服務器:“漲了!”
這就像你每隔2秒就打電話問朋友:“有消息嗎?” —— 效率低、費流量、延遲高。
WebSocket 是什么?
可以理解為你和服務器開了一個“專線通話”:
首次連接時,用HTTP協(xié)議握手(打個招呼建立連接)
連接保持不中斷,服務器可以隨時主動給你發(fā)消息,你也能隨時發(fā)消息給服務器
實時雙向通信,不再需要反復問“有消息嗎?”
就像你和朋友微信語音通話,接通后雙方隨時都能說話,不用掛斷重撥。
實際場景:
聊天軟件(微信、釘釘):消息秒達,不用刷新頁面
股票實時行情:股價變動立即推送到你屏幕
協(xié)同編輯(如騰訊文檔):多人編輯時內容實時同步
2. 環(huán)境搭建
在 Spring Boot 與 Vue 整合 WebSocket 消息通知的場景中,通常Spring Boot 項目作為服務端,而 Vue 項目作為客戶端。這種架構設計的原因如下:
Spring Boot(服務端):負責消息處理、業(yè)務邏輯、數(shù)據(jù)持久化,以及與 WebSocket 客戶端的連接管理。
Vue(客戶端):通過瀏覽器提供用戶界面,并使用 JavaScript 的 WebSocket API 連接到服務端,接收和展示消息。
2.1 Vue 項目
在 Vue 項目中,我們使用 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(); }); } }); } // 關閉連接 export function disconnectWebSocket() { if (stompClient !== null) { stompClient.disconnect(); } }
2.2 SpringBoot 項目
添加依賴
<!-- 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實現(xiàn)Web實時消息推送功能的詳細內容,更多關于Vue3 SpringBoot Web消息推送的資料請關注腳本之家其它相關文章!
相關文章
Vue實現(xiàn)添加數(shù)據(jù)到二維數(shù)組并顯示
這篇文章主要介紹了Vue實現(xiàn)添加數(shù)據(jù)到二維數(shù)組并顯示方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04ElementUI+命名視圖實現(xiàn)復雜頂部和左側導航欄
本文主要介紹了ElementUI+命名視圖實現(xiàn)復雜頂部和左側導航欄,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-04-04window.onresize在vue中只能使用一次,自適應resize報錯問題
這篇文章主要介紹了window.onresize在vue中只能使用一次,自適應resize報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10