SSE Emitter在Spring Boot和Vue中的简单使用

1、确保你的 pom.xml 包含 Spring Web 依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2、创建 SSE 控制器

java 复制代码
package com.keran.wms.controller;

import cn.hutool.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.*;

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

    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    // 客户端连接端点
    @GetMapping(path = "/connect")
    public SseEmitter connect() {
        SseEmitter emitter = new SseEmitter(60_000L); // 超时时间60秒

        emitter.onCompletion(() -> emitters.remove(emitter));
        emitter.onTimeout(() -> emitters.remove(emitter));

        emitters.add(emitter);

        return emitter;
    }

    // 向所有客户端发送消息
    public void sendEventToAll(String data) {
        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(SseEmitter.event()
                        .data(data)
                        .name("message")); // 事件名称
            } catch (IOException e) {
                emitter.complete();
                emitters.remove(emitter);
            }
        }
    }

    // 测试发送消息的端点
    @GetMapping("/send")
    public JSONObject sendMessage() {
        sendEventToAll("Server time: " + System.currentTimeMillis());
        return new JSONObject().set("status", "Message sent to all clients");
    }

    // 每20秒发送一次心跳
    @Scheduled(fixedRate = 20000)
    public void sendHeartbeat() {
        emitters.forEach(emitter -> {
            try {
                emitter.send(SseEmitter.event()
                        .data("heartbeat")
                        .reconnectTime(5000L)); // 建议的重连时间
            } catch (IOException e) {
                emitter.completeWithError(e);
                emitters.remove(emitter);
            }
        });
    }

}

3、前端Vue实现

html 复制代码
<template>
  <div>
    <h1>SSE Demo</h1>
    <div v-for="(message, index) in messages" :key="index">
      {{ message }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      eventSource: null,
      reconnectDelay: 5000,
    };
  },
  mounted() {
    this.connectSSE();
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  methods: {
    connectSSE() {
      // 替换为你的Spring Boot后端地址
      this.eventSource = new EventSource('http://localhost:8080/sse/connect');
      
      // 通用消息处理器
      this.eventSource.onmessage = (event) => {
        this.messages.push(event.data);
      };
      
      // 特定事件处理器(对应后端.name()设置的事件名)
      this.eventSource.addEventListener('message', (event) => {
        this.messages.push(event.data);
      });
      
      // 错误处理
      this.eventSource.onerror = (error) => {
        this.eventSource.close();
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            setTimeout(() => {
            this.reconnectAttempts++;
            this.connectSSE();
        }, this.reconnectDelay);
      }
      };
    }
  }
};
</script>

4、访问 http://localhost:6065/sse/send测试

5、测试成功

相关推荐
程序员小杰@28 分钟前
【MCP教程系列】SpringBoot 搭建基于 Spring AI 的 SSE 模式 MCP 服务
人工智能·spring boot·spring
程序员buddha1 小时前
Spring & Spring Boot 常用注解整理
java·spring boot·spring
程序员与背包客_CoderZ1 小时前
Node.js异步编程——Callback回调函数实现
前端·javascript·node.js·web
C_V_Better2 小时前
Java Spring Boot 控制器中处理用户数据详解
java·开发语言·spring boot·后端·spring
非凡ghost2 小时前
Pale Moon:速度优化的Firefox定制浏览器
前端·firefox
胡子洲2 小时前
Spring Boot 应用中实现基本的 SSE 功能
java·spring boot·后端
清灵xmf2 小时前
从 Set、Map 到 WeakSet、WeakMap 的进阶之旅
前端·javascript·set·map·weakset·weakmap
非著名架构师2 小时前
SpringBoot整合MQTT实战:基于EMQX构建高可靠物联网通信,从零到一实现设备云端双向对话
spring boot·mqtt·emqx
贰拾wan2 小时前
【Java-EE进阶】SpringBoot针对某个IP限流问题
java·spring boot·后端·idea
11054654013 小时前
11、参数化三维产品设计组件 - /设计与仿真组件/parametric-3d-product-design
前端·3d