在 Spring Boot 中实现服务器端推送(SSE):两种方法的比较与实践

发布于:2025-04-14 ⋅ 阅读:(23) ⋅ 点赞:(0)

在现代 Web 应用中,实时数据推送是一个常见的需求。无论是实时消息通知、股票行情更新,还是在线游戏的实时数据交互,服务器端推送(Server-Sent Events,简称 SSE)都是一种高效且易于实现的解决方案。在 Spring Boot 中,有两种主要方式可以实现 SSE:使用 SseEmitter 和使用 Spring WebFlux。本文将详细介绍这两种方法的实现步骤,并比较它们的优缺点,帮助你在实际开发中选择合适的技术方案。

一、什么是 Server-Sent Events(SSE)

Server-Sent Events 是一种允许服务器向客户端推送实时更新的技术。与传统的轮询或长轮询相比,SSE 提供了一种更高效、更轻量级的解决方案。SSE 使用 HTTP 协议,客户端通过一个简单的 EventSource 接口订阅服务器端的事件流,服务器端则通过持续的 HTTP 连接向客户端发送数据。

SSE 的主要特点包括:

  • 单向通信:数据从服务器流向客户端。
  • 轻量级:基于 HTTP,不需要额外的 WebSocket 协议支持。
  • 自动重连:客户端在连接断开后会自动尝试重新连接。
  • 跨浏览器支持:现代浏览器普遍支持 SSE。

二、使用 SseEmitter 实现 SSE

SseEmitter 是 Spring 提供的一个工具类,用于实现 SSE。它允许你手动管理每个客户端的连接,并向它们推送数据。

1. 添加依赖

确保你的 Spring Boot 项目中包含以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 创建控制器

创建一个控制器来管理 SSE 连接和推送消息:

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.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
public class SSEController {

    private final Map<String, SseEmitter> emitters = Collections.synchronizedMap(new HashMap<>());

    @GetMapping("/sse/connect/{clientId}")
    public SseEmitter connect(@PathVariable String clientId) {
        SseEmitter emitter = new SseEmitter();
        emitters.put(clientId, emitter);

        emitter.onCompletion(() -> emitters.remove(clientId));
        emitter.onTimeout(() -> emitters.remove(clientId));
        emitter.onError(e -> emitters.remove(clientId));

        return emitter;
    }

    @GetMapping("/sse/send/{clientId}")
    public void sendMessage(@PathVariable String clientId) {
        SseEmitter emitter = emitters.get(clientId);
        if (emitter != null) {
            try {
                emitter.send(SseEmitter.event().data("Hello, client " + clientId + "!"));
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        }
    }
}

3. 前端实现

在前端页面中,使用 EventSource 来订阅 SSE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Example</title>
</head>
<body>
<div id="messages"></div>
<script>
    const eventSource = new EventSource('/sse/connect/client1');
    eventSource.onmessage = function(event) {
        const messagesDiv = document.getElementById('messages');
        const newMessage = document.createElement('p');
        newMessage.textContent = event.data;
        messagesDiv.appendChild(newMessage);
    };
    eventSource.onerror = function(err) {
        console.error("Error:", err);
        eventSource.close();
    };
</script>
</body>
</html>

三、使用 Spring WebFlux 实现 SSE

Spring WebFlux 提供了更简洁的方式来实现 SSE,利用响应式编程模型。

1. 添加依赖

确保你的项目中包含 WebFlux 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2. 创建控制器

使用 Flux 来生成数据流:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.time.LocalTime;

@RestController
public class FluxController {

    @GetMapping(value = "/stream/time", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamTime() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> "Current Time: " + LocalTime.now());
    }
}

3. 前端实现

前端代码与使用 SseEmitter 的实现类似,使用 EventSource 来订阅数据流:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Time Stream</title>
</head>
<body>
<h1>实时推送当前时间</h1>
<ul id="time-list"></ul>
<script>
    const eventSource = new EventSource('/stream/time');
    eventSource.onmessage = function(event) {
        const timeList = document.getElementById('time-list');
        const listItem = document.createElement('li');
        listItem.textContent = event.data;
        timeList.appendChild(listItem);
    };
    eventSource.onerror = function(error) {
        console.error('Error:', error);
        eventSource.close();
    };
</script>
</body>
</html>

四、两种方法的比较

1. 灵活性

  • SseEmitter:提供了更高的灵活性,允许你手动管理每个客户端的连接,适合需要对每个客户端进行精细控制的场景。
  • Spring WebFlux:更适合生成连续的数据流,代码更简洁,适合响应式编程场景。

2. 性能

  • SseEmitter:基于传统的 Spring MVC,适合处理少量客户端连接。
  • Spring WebFlux:基于响应式编程模型,适合处理大量并发连接,性能更高。

3. 易用性

  • SseEmitter:代码相对复杂,需要手动管理连接和错误处理。
  • Spring WebFlux:代码更简洁,利用 FluxMono 提供了更强大的功能。

五、总结

在 Spring Boot 中实现 SSE 有多种方式,选择哪种方式取决于你的具体需求。如果你需要对每个客户端进行精细控制,SseEmitter 是一个不错的选择。如果你需要处理大量并发连接,或者希望代码更简洁,Spring WebFlux 是一个更好的选择。

希望本文能帮助你在实际开发中更好地实现 SSE,为你的应用带来更实时、更高效的用户体验。

参考资料

如果你有任何问题或建议,请随时在评论区留言,我会尽快回复。


网站公告

今日签到

点亮在社区的每一天
去签到