SpringBoot+Vue3整合SSE实现实时消息推送

 更新时间:2026年03月12日 15:17:43   作者:每日技术  
这篇文章主要为大家详细介绍了SpringBoot+Vue3整合SSE实现实时消息推送的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

我把 SpringBoot + Vue3 整合 SSE​ 的文章写得更加详细,包括依赖引入、配置说明、完整代码、测试方法和注意事项,让你真正可以“一分钟开箱即用”。

一、技术原理简介

SSE(Server-Sent Events) ​ 是一种基于 HTTP 的服务器向客户端单向实时通信技术。

特点:

  • 基于标准 HTTP 协议,无需 WebSocket 复杂握手。
  • 服务端保持长连接,随时推送数据。
  • 浏览器原生支持 EventSourceAPI。
  • 适合 通知推送、实时日志、股票行情、聊天消息(单向) ​ 等场景。

二、后端:SpringBoot 实现 SSE

1. 引入依赖

使用 Maven 的 pom.xml引入 Spring Boot Web 依赖(Spring Boot 自带 SSE 支持,无需额外 jar):

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 测试用:方便发 POST 请求 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

说明spring-boot-starter-web已经包含了 javax.servlet-api和 Spring MVC,SseEmitter类位于 org.springframework.web.servlet.mvc.method.annotation.SseEmitter,无需额外引入 jar。

2. 配置文件

application.yml(或 application.properties)保持默认即可,无需特殊配置。

如果需要跨域,可以加:

spring:
  web:
    cors:
      allowed-origins: "*"

3. SSE 控制器代码

package com.example.sse.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/sse")
public class SseController {

    // 保存每个用户的 SSE 连接,生产环境可用 Redis 等分布式缓存
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    /**
     * 客户端订阅接口
     * GET /sse/subscribe/{userId}
     */
    @GetMapping(value = "/subscribe/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter subscribe(@PathVariable String userId) {
        // 0 表示永不超时,如需超时可用 60_000 毫秒
        SseEmitter emitter = new SseEmitter(0L);
        emitters.put(userId, emitter);

        // 完成时移除
        emitter.onCompletion(() -> emitters.remove(userId));
        // 超时移除
        emitter.onTimeout(() -> emitters.remove(userId));
        // 出错移除
        emitter.onError((e) -> emitters.remove(userId));

        return emitter;
    }

    /**
     * 服务端推送消息接口
     * POST /sse/push/{userId}
     */
    @PostMapping("/push/{userId}")
    public void push(@PathVariable String userId, @RequestBody String message) {
        SseEmitter emitter = emitters.get(userId);
        if (emitter != null) {
            try {
                // name("message") 对应前端的 event type
                emitter.send(SseEmitter.event().name("message").data(message));
            } catch (IOException e) {
                emitters.remove(userId);
            }
        }
    }
}

4. 启动类

package com.example.sse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SseApplication {
    public static void main(String[] args) {
        SpringApplication.run(SseApplication.class, args);
    }
}

三、前端:Vue3 连接 SSE

1. 创建 Vue3 项目

npm create vite@latest sse-demo -- --template vue
cd sse-demo
npm install

2. 组件代码

src/components/SseDemo.vue

<template>
  <div>
    <h3>SSE 实时消息推送</h3>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
const messages = ref([])
let eventSource = null
onMounted(() => {
  // 替换为你的后端地址和 userId
  eventSource = new EventSource('http://localhost:8080/sse/subscribe/user123')
  // 接收消息
  eventSource.onmessage = (event) => {
    messages.value.push(event.data)
  }
  // 错误处理
  eventSource.onerror = (err) => {
    console.error('SSE connection error:', err)
    eventSource.close()
  }
})
onBeforeUnmount(() => {
  if (eventSource) {
    eventSource.close()
  }
})
</script>

3. 在 App.vue 中使用

<template>
  <SseDemo />
</template>
<script setup>
import SseDemo from './components/SseDemo.vue'
</script>

四、测试方法

1.启动 SpringBoot 后端​:默认端口 8080。

2.启动 Vue3 前端

npm run dev

打开浏览器访问 http://localhost:5173

3.发送测试消息

用 Postman 或 curl 发 POST 请求:

curl -X POST http://localhost:8080/sse/push/user123 \
-H "Content-Type: application/json" \
-d '"Hello SSE 实时消息!"'

前端页面会立刻收到并显示消息。

五、注意事项与优化

跨域问题​:前后端分离时,后端需配置 CORS,否则浏览器会拦截 EventSource 连接。

心跳保活​:长时间无消息时,连接可能被代理或浏览器断开。可在服务端定时推送注释行保持活跃:

emitter.send(SseEmitter.event().comment("heartbeat"));

多用户广播​:当前示例是点对点(一个用户一个连接),如需群发,可维护一个 List<SseEmitter>或按频道分组。

生产环境

  • 使用 Redis 或消息队列管理连接,支持集群。
  • 设置合理的超时时间与重连机制。
  • 对敏感消息加密传输(HTTPS)。

总结

  • 后端:SseEmitter+ @GetMapping(produces=TEXT_EVENT_STREAM_VALUE)
  • 前端:new EventSource(url)+ onmessage接收
  • 引入 jar:仅需 spring-boot-starter-web,零额外依赖。

到此这篇关于SpringBoot+Vue3整合SSE实现实时消息推送的文章就介绍到这了,更多相关SpringBoot SSE实时消息推送内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • MyBatis-Plus详解(环境搭建、关联操作)

    MyBatis-Plus详解(环境搭建、关联操作)

    MyBatis-Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生,今天通过本文给大家介绍MyBatis-Plus环境搭建及关联操作,需要的朋友参考下吧
    2022-09-09
  • Netty解决半包和粘包问题的方案

    Netty解决半包和粘包问题的方案

    Netty 是一个高性能、异步事件驱动的网络应用框架,广泛应用于各种网络通信场景,这篇文章,我们将详细分析 Netty 是如何解决半包和粘包问题,文中通过代码示介绍的非常详细,需要的朋友可以参考下
    2024-08-08
  • Java servlet后端开发超详细教程

    Java servlet后端开发超详细教程

    Servlet指在服务器端执行的一段Java代码,可以接收用户的请求和返回给用户响应结果,下面这篇文章主要给大家介绍了关于Java.servlet生命周期的相关资料,需要的朋友可以参考下
    2023-02-02
  • java项目中的多线程实践记录

    java项目中的多线程实践记录

    项目开发中对于一些数据的处理需要用到多线程,比如文件的批量上传,数据库的分批写入,大文件的分段下载等,主要涉及到多线程的一些知识,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下
    2021-11-11
  • Java SpringBoot高级用法详解

    Java SpringBoot高级用法详解

    这篇文章主要为大家详细介绍了Java Spring Boot的一些高级用法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-09-09
  • 浅析Java数据库操作工具包jOOQ的使用

    浅析Java数据库操作工具包jOOQ的使用

    jOOQ 是一个轻量级的 Java ORM(对象关系映射)框架,可用来构建复杂的 SQL 查询,这篇文章主要来和大家介绍一下jOOQ的使用,需要的可以参考下
    2024-04-04
  • Springboot如何通过路径映射获取本机图片资源

    Springboot如何通过路径映射获取本机图片资源

    项目中对图片的处理与查看是必不可少的,本文将讲解如何通过项目路径来获取到本机电脑的图片资源,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2023-08-08
  • Spring事务失效的几种原因

    Spring事务失效的几种原因

    在日常编码过程中常常涉及到事务,在前两天看到一篇文章提到了Spring事务,那么在此总结下在Spring环境下事务失效的几种原因.
    2020-09-09
  • springMVC中HttpMessageConverter的具体使用

    springMVC中HttpMessageConverter的具体使用

    HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,本文主要介绍了springMVC中HttpMessageConverter的具体使用,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • 在Java的Struts中判断是否调用AJAX及用拦截器对其优化

    在Java的Struts中判断是否调用AJAX及用拦截器对其优化

    这篇文章主要介绍了在Java的Struts中判断是否调用AJAX及用拦截器对其优化的方法,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
    2016-01-01

最新评论