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

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监听事件的类型需要与后端发送的类型一致

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

  • 16
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个基于 Spring Boot、WebSocket 和 Vue 实现后端实时向前端推送数据的代码示例: 1. 后端代码 ``` @Controller public class WebSocketController { private final WebSocketService webSocketService; @Autowired public WebSocketController(WebSocketService webSocketService) { this.webSocketService = webSocketService; } @GetMapping("/") public String index() { return "index"; } @Scheduled(fixedDelay = 1000) public void pushData() { webSocketService.sendAll(String.valueOf(System.currentTimeMillis())); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` ``` @Service public class WebSocketService { private final List<Session> sessions = new CopyOnWriteArrayList<>(); public void add(Session session) { sessions.add(session); } public void remove(Session session) { sessions.remove(session); } public void sendAll(String message) { sessions.forEach(session -> { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } }); } } ``` 2. 前端代码 ``` <template> <div> <h1>Real-time data:</h1> <ul> <li v-for="(data, index) in dataList" :key="index">{{ data }}</li> </ul> </div> </template> <script> export default { data() { return { dataList: [] } }, mounted() { const ws = new WebSocket('ws://localhost:8080/ws'); ws.onmessage = (event) => { this.dataList.push(event.data); }; ws.onclose = () => { console.log('Connection closed'); }; } } </script> ``` 在这个示例中,我们在后端创建了一个定时任务,每秒钟向所有连接上的客户端推送当前时间戳。我们还创建了一个 WebSocketService,用于管理客户端连接和消息发送。 在前端,我们通过 Vue 的 mounted 生命周期创建了一个 WebSocket 连接,并在每次接收到服务器发来的消息时将其添加到一个数据列表中,然后在模板中通过 v-for 渲染出来。 要注意的是,我们在前端中只创建了一个 WebSocket 连接,用于接收服务器推送数据。这是因为 WebSocket 是全双工通信,可以同时进行发送和接收操作。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值