【SpringBoot+SseEmitter】 和【Vue3+EventSource】 实时数据推送

本文介绍了如何在SpringBoot中使用SseEmitter实现服务端实时推送,并展示了Vue3如何对接EventSource接收数据,包括跨域处理、连接设置和常见问题解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EventSource 的优点

  1. 简单易用:EventSource 使用简单,基于标准的 HTTP 协议,无需复杂的握手过程。
  2. 自动重连:EventSource 具有内置的重连机制,确保连接中断后自动重新连接。
  3. 轻量级:EventSource 使用长轮询机制,消耗的资源相对较少,适合低带宽环境。
  4. 跨域支持:EventSource 允许在跨域环境下进行通信,通过适当的响应头授权来自不同域的客户端连接。

1、SpringBoot实现SseEmitter

1.1简易业务层


import org.springframework.http.MediaType;
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.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author tm
 * Date 2023/9/25
 * Version 1.0
 */
@RestController
@RequestMapping(path = "/sysTest/see")
public class SseControllerTest {
    private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();


    /**
     * 前端传递标识,生成唯一的消息通道
     */
    @GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter push(String id) throws IOException {
        // 超时时间设置为3s,用于演示客户端自动重连
        SseEmitter sseEmitter = new SseEmitter(30000L);
        // 设置前端的重试时间为1s
        sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("连接成功"));
        sseCache.put(id, sseEmitter);
        System.out.println("add " + id);
        sseEmitter.onTimeout(() -> {
            System.out.println(id + "超时");
            sseCache.remove(id);
        });
        sseEmitter.onCompletion(() -> System.out.println("完成!!!"));
        return sseEmitter;
    }

    /**
     * 根据标识传递信息
     */
    @GetMapping(path = "push")
    public String push(String id, String content) throws IOException {
        SseEmitter sseEmitter = sseCache.get(id);
        if (sseEmitter != null) {
            sseEmitter.send(SseEmitter.event().name("msg").data("后端发送消息:" + content));
        }
        return "over";
    }

    /**
     * 根据标识移除SseEmitter
     */
    @GetMapping(path = "over")
    public String over(String id) {
        SseEmitter sseEmitter = sseCache.get(id);
        if (sseEmitter != null) {
            sseEmitter.complete();
            sseCache.remove(id);
        }
        return "over";
    }
}

2、Vue3对接EventSource

const  initEventSource = ()=>{
  if (typeof (EventSource) !== 'undefined') {
    const evtSource = new EventSource('https://xxx.xxx.x.x/sysTest/see/subscribe?id=002', { withCredentials: true }) // 后端接口,要配置允许跨域属性
    // 与事件源的连接刚打开时触发
    evtSource.onopen = function(e){
      console.log(e);
    }

    // 当从事件源接收到数据时触发
    evtSource.onmessage = function(e){
      console.log(e);
    }
    // 与事件源的连接无法打开时触发
    evtSource.onerror = function(e){
      console.log(e);
      evtSource.close(); // 关闭连接
    }
    // 也可以侦听命名事件,即自定义的事件
    evtSource.addEventListener('msg', function(e) {
      console.log(e.data)
    })
  } else {
    console.log('当前浏览器不支持使用EventSource接收服务器推送事件!');
  }

  
}

3、测试、验证、使用

使用postMan调用接口测试

3.1、 postMan调用后端"push"接口发送消息

在这里插入图片描述

3.2、前端实时接收到数据

在这里插入图片描述

4、踩坑

4.1、nginx对于EventSource连接要特殊处理

#eventSource
location /es/ {
    proxy_pass  http://请求地址/;
    #必须要设置当前Connection 属性
    proxy_set_header Connection '';
    proxy_http_version 1.1;
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;
}

4.2、连接通道接口类型一定要设置MediaType.TEXT_EVENT_STREAM_VALUE

在这里插入图片描述

4.3、 跨越问题,项目地址和接口地址需要在同一域名下

在这里插入图片描述

4.4 、EventSource监听事件的类型需要与后端发送的类型一致

在这里插入图片描述
在这里插入图片描述

创作不易,感谢点赞
创作不易,感谢点赞
创作不易,感谢点赞
创作不易,感谢点赞
创作不易,感谢点赞
创作不易,感谢点赞

### 实现 Spring Boot Vue 之间流式输出 (SSE) #### 后端:Spring Boot 配置 为了实现在 Spring Boot 中发送 Server-Sent Events(SSE),可以创建一个控制器来广播消息给前端客户端。下面是一个简单的例子: ```java import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SseController { @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> stream() { return Flux.interval(Duration.ofSeconds(1)) .map(sequence -> "data: Message at time " + LocalDateTime.now()); } } ``` 这段代码定义了一个 REST 控制器,它通过 `/stream` 路径暴露了一个 SSE 终结点[^1]。 对于更复杂的场景,可能需要管理多个连接或向特定会话推送数据,在这种情况下应该考虑使用 `SseEmitter` 或者其他高级特性。 #### 前端:Vue.js 使用 EventSource API 接收更新 在 Vue 应用程序里可以通过 JavaScript 的内置对象 `EventSource` 来接收来自服务器的消息。这里展示怎样在一个组件内部初始化并监听这些事件: ```javascript export default { name: &#39;App&#39;, mounted () { const eventSource = new EventSource(&#39;/stream&#39;); eventSource.onmessage = function(event) { console.log(`New message from server: ${event.data}`); }; eventSource.onerror = function(error) { console.error(&#39;Error occurred:&#39;, error); eventSource.close(); }; }, unmounted () { this.eventSource?.close(); // 清理资源 } }; ``` 此片段展示了如何建立到后端的持久化连接以及当接收到新信息时执行的操作。 由于原生 `EventSource` 存在局限性,如果项目需求超出其能力范围,则建议寻找第三方库作为替代方案,比如 [EventSourcePolyfill](https://github.com/Yaffle/EventSource)。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值