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、测试成功

相关推荐
MediaTea21 小时前
Jupyter Notebook:基于 Web 的交互式编程环境
前端·ide·人工智能·python·jupyter
少年阿闯~~21 小时前
CSS——重排和重绘
前端
奶糖 肥晨21 小时前
Uniapp 开发中遭遇「可选链赋值」语法陷阱:一次编译错误排查实录
javascript·vue.js·uni-app
个人看法21 小时前
h5实现一个吸附在键盘上的工具栏
前端·javascript·vue
belldeep1 天前
python:Django 和 Vue.js 技术栈解析
vue.js·python·django
知识分享小能手1 天前
微信小程序入门学习教程,从入门到精通,微信小程序页面制作(2)
前端·javascript·学习·微信小程序·小程序·前端框架·notepad++
jason_yang1 天前
JavaScript 风格指南 精选版
前端·javascript·代码规范
在未来等你1 天前
Kafka面试精讲 Day 24:Spring Kafka开发实战
java·spring boot·面试·kafka·消息队列·spring kafka·@kafkalistener
小高0071 天前
🔍ECMAScript 2025 有哪些新特性?
前端·javascript
正义的大古1 天前
OpenLayers地图交互 -- 章节十七:键盘缩放交互详解
javascript·vue.js·openlayers