Spring Boot 3 + Vue 3 + WebSocket(STOMP) 实时消息推送骨架

0 阅读1分钟

一、后端(Spring Boot)

1️⃣ 依赖 pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2️⃣ WebSocket 配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
        registry.setUserDestinationPrefix("/user");
    }
}

3️⃣ 消息推送 Service

@Service
public class PushService {
    @Autowired
    private SimpMessagingTemplate template;

    // 广播
    public void broadcast(String msg) {
        template.convertAndSend("/topic/notice", msg);
    }

    // 点对点(需绑定 Principal)
    public void sendToUser(String username, Object msg) {
        template.convertAndSendToUser(username, "/queue/msg", msg);
    }
}

4️⃣ 测试 Controller

@RestController
public class TestController {
    @Autowired PushService pushService;

    @GetMapping("/push")
    public void push(String msg) {
        pushService.broadcast(msg);
    }
}

二、前端(Vue 3)

1️⃣ 安装依赖

npm i sockjs-client @stomp/stompjs

2️⃣ WebSocket 工具封装 utils/ws.js

import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'
import { ref } from 'vue'

export const wsConnected = ref(false)
let client = null

export function connectWs() {
  client = new Client({
    webSocketFactory: () => new SockJS('http://localhost:8080/ws'),
    reconnectDelay: 5000,
    onConnect: () => {
      wsConnected.value = true
      // 广播订阅
      client.subscribe('/topic/notice', m => {
        console.log('广播消息:', m.body)
      })
      // 点对点订阅(登录后替换 userId)
      client.subscribe('/user/queue/msg', m => {
        console.log('私信:', m.body)
      })
    }
  })
  client.activate()
}

export function disconnectWs() {
  client?.deactivate()
}

3️⃣ 在 App.vue中连接

import { connectWs } from '@/utils/ws'
connectWs()

三、快速验证

  1. 启动 Spring Boot(默认 8080)

  2. 启动 Vue(npm run dev

  3. 浏览器访问 → 控制台看到 STOMP CONNECTED

  4. 调接口触发广播:

    GET http://localhost:8080/push?msg=hello

→ Vue 控制台打印 广播消息: hello

四、企业级扩展建议

需求

做法

JWT 鉴权

ChannelInterceptor拦截 CONNECT 解析 Token 绑定 Principal

集群推送

Redis Pub/Sub + enableSimpleBroker或 RabbitMQ 外部 Broker

消息持久化

推送前写 DB/ES,前端做已读 ACK

心跳/重连

@stomp/stompjs已内置 reconnectDelay

前端弹窗

window.Notification或 Element Plus $notify

如果你想我再补 JWT 鉴权版Redis 集群版,或直接给你一个 GitHub 最小 Demo 项目结构,告诉我即可 👍