Vue3和SpringBoot实现Web实时消息推送,一点都不难!

0 阅读2分钟

1.前言

先看演示效果:后端发送消息,前端实时展示

1.1 WebSocket

WebSocket 是一种常用的实现 web 实时消息推送的技术。

我们先看**传统网站(HTTP)**的缺点:

假设你打开一个股票网站,网页会反复问服务器:“股价变了吗?”(刷新请求) → 服务器:“没变”(响应)... 过2秒网页又问:“变了吗?”... 服务器:“涨了!”

这就像你每隔2秒就打电话问朋友:“有消息吗?” —— 效率低、费流量、延迟高。

WebSocket 是什么?

可以理解为你和服务器开了一个“专线通话”:

  • 首次连接时,用HTTP协议握手(打个招呼建立连接)

  • 连接保持不中断,服务器可以随时主动给你发消息,你也能随时发消息给服务器

  • 实时双向通信,不再需要反复问“有消息吗?”

  • 就像你和朋友微信语音通话,接通后双方随时都能说话,不用挂断重拨。

实际场景:

  • 聊天软件(微信、钉钉):消息秒达,不用刷新页面

  • 股票实时行情:股价变动立即推送到你屏幕

  • 协同编辑(如腾讯文档):多人编辑时内容实时同步

2. 环境搭建

在 Spring Boot 与 Vue 整合 WebSocket 消息通知的场景中,通常Spring Boot 项目作为服务端,而 Vue 项目作为客户端。这种架构设计的原因如下:

  • Spring Boot(服务端):负责消息处理、业务逻辑、数据持久化,以及与 WebSocket 客户端的连接管理。

  • Vue(客户端):通过浏览器提供用户界面,并使用 JavaScript 的 WebSocket API 连接到服务端,接收和展示消息。

2.1 Vue 项目

在 Vue 项目中,我们使用 sockjs-client 和 stomp.js 库来连接 WebSocket。

npm install sockjs-client stompjs

创建 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");
        // 客户端发送消息的路径前缀
        registry.setApplicationDestinationPrefixes("/app");
    }

}

3. 核心代码

3.1 后端

// 注入依赖
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
// 发送消息
simpMessagingTemplate.convertAndSend("/topic/new-orders"",orderNumber);
// 向特定客户发送消息
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();
});

前端页面显示连接成功