Vue3结合SpringBoot打造一个高效Web实时消息推送系统
作者:星辰聊技术
这篇文章主要为大家详细介绍了Vue3如何结合SpringBoot打造一个高效Web实时消息推送系统,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
在传统的 HTTP 通信模型中,客户端想要获取最新数据,必须不断地向服务器发送请求进行询问——这种方式称为轮询。
假设你正在访问一个股票信息平台,浏览器每隔数秒就向服务器发送请求,服务器回复:“暂时没变化”,直到股价真正变化为止。这不仅浪费带宽,也带来了数据更新的延迟。
而 WebSocket 则从根本上改变了这个机制。它在客户端与服务器之间建立一条持久连接,允许服务端主动将新消息推送给客户端。这就像双方之间开了一个微信语音通话频道,消息来回即时互通,无需每次“挂断再拨号”。
典型应用场景:
- 实时聊天(如微信、钉钉)
- 股票/币价推送
- 实时协作文档编辑
- 在线订单通知/预警系统
系统构建:技术选型与项目结构
为了实现一个具有实时消息推送能力的 Web 应用,我们采用如下架构:
- 服务端(Spring Boot):负责业务逻辑处理、WebSocket 消息分发和管理连接会话。
- 客户端(Vue3):负责 UI 展示和 WebSocket 的消息接收/显示。
Spring Boot 服务端实现
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"); } }
消息推送服务
@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 前端实现
安装依赖
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>
部署上线实战
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 打包和环境变量
const socket = new SockJS(import.meta.env.VITE_WS_ENDPOINT || "http://localhost:8083/ws-notification");
WebSocket 鉴权机制
服务端 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); }); });
总结
通过本项目的实战与优化,我们打造了一个功能完整的实时消息推送系统,它具备如下特性:
- 前后端解耦,通信基于 WebSocket + STOMP
- 消息反应秒级可达
- 支持鉴权,可与登陆系统完编合
- 具备断线重连能力
- 可实际部署,用 Nginx 做网关分发
到此这篇关于Vue3结合SpringBoot打造一个高效Web实时消息推送系统的文章就介绍到这了,更多相关Vue3 SpringBoot消息推送内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!