欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3結(jié)合SpringBoot打造一個(gè)高效Web實(shí)時(shí)消息推送系統(tǒng)

 更新時(shí)間:2025年07月01日 10:58:58   作者:星辰聊技術(shù)  
這篇文章主要為大家詳細(xì)介紹了Vue3如何結(jié)合SpringBoot打造一個(gè)高效Web實(shí)時(shí)消息推送系統(tǒng),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

在傳統(tǒng)的 HTTP 通信模型中,客戶端想要獲取最新數(shù)據(jù),必須不斷地向服務(wù)器發(fā)送請(qǐng)求進(jìn)行詢(xún)問(wèn)——這種方式稱(chēng)為輪詢(xún)。

假設(shè)你正在訪問(wèn)一個(gè)股票信息平臺(tái),瀏覽器每隔數(shù)秒就向服務(wù)器發(fā)送請(qǐng)求,服務(wù)器回復(fù):“暫時(shí)沒(méi)變化”,直到股價(jià)真正變化為止。這不僅浪費(fèi)帶寬,也帶來(lái)了數(shù)據(jù)更新的延遲。

而 WebSocket 則從根本上改變了這個(gè)機(jī)制。它在客戶端與服務(wù)器之間建立一條持久連接,允許服務(wù)端主動(dòng)將新消息推送給客戶端。這就像雙方之間開(kāi)了一個(gè)微信語(yǔ)音通話頻道,消息來(lái)回即時(shí)互通,無(wú)需每次“掛斷再撥號(hào)”。

典型應(yīng)用場(chǎ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ā)和管理連接會(huì)話。
  • 客戶端(Vue3):負(fù)責(zé) UI 展示和 WebSocket 的消息接收/顯示。

Spring Boot 服務(wù)端實(shí)現(xiàn)

Maven 依賴(lài)

<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)

安裝依賴(lài)

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("無(wú)效的 Token");
            }


            accessor.setUser(new UsernamePasswordAuthenticationToken("user", null, new ArrayList<>()));
        }
        return message;
    }
}

在 WebSocket 配置中注冊(cè)

@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é)

通過(guò)本項(xiàng)目的實(shí)戰(zhàn)與優(yōu)化,我們打造了一個(gè)功能完整的實(shí)時(shí)消息推送系統(tǒng),它具備如下特性:

  • 前后端解耦,通信基于 WebSocket + STOMP
  • 消息反應(yīng)秒級(jí)可達(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論