【WebSocket平替,支持单项传播】Spring Boot 响应式 SSE 实时推送,单机吞吐量10万+

参考

Spring Boot 响应式 SSE 实时推送,单机吞吐量10万+

概念

在高并发场景下,Spring Boot 结合 响应式编程(WebFlux) + SSE(Server-Sent Events) 是实现实时推送的最优方案之一 ——SSE 基于 HTTP 长连接,仅服务器向客户端单向推送,开销远低于 WebSocket(无需双工通信),而 WebFlux 的非阻塞响应式模型能支撑海量并发连接(单机轻松突破 10 万 + 吞吐量)。

SSE对比WebSocket

特性SSE (Server-Sent Events)WebSocket
通信方向单向(服务器→客户端)双向(全双工)
协议基础基于 HTTP(复用端口、兼容代理)独立 TCP 协议(需额外端口)
连接开销低(长连接复用,无握手开销)中(需 TCP 握手 + WebSocket 握手)
并发支撑高(非阻塞模型下连接数无上限)中(双工通信占用更多资源)
适用场景实时通知、行情推送、日志流聊天、实时协作(需双向交互)

总结

Spring Boot WebFlux + SSE 是高并发实时推送的最优解之一,核心优势:

轻量高效:基于 HTTP 长连接,无需额外协议,兼容性好;
高并发支撑:响应式非阻塞模型,单机轻松突破 10 万 + 连接;
开发简单:WebFlux 原生支持 SSE,无需复杂配置;
资源可控:通过连接超时、心跳机制、权限控制避免资源滥用。
适用场景:实时通知、行情推送、日志流、数据看板等单向推送场景。如果需要双向交互(如聊天),则需选择 WebSocket。

实战SpringBoot3_WebFlux_SSE

定义pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.edevp</groupId>
    <artifactId>SpringBoot3_WebFlux_SSE</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>17</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version> <!-- 推荐 3.x(支持 Reactor 3.6+) -->
    </parent>

    <dependencies>
        <!-- 响应式 Web 核心依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <!-- 工具类(可选) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>


    <distributionManagement>
        <repository>
            <id>wsl-nexus-releases</id>
            <name>Nexus Release Repository</name>
            <url>http://127.0.0.1:8081/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>wsl-nexus-snapshots</id>
            <name>Nexus Snapshot Repository</name>
            <url>http://127.0.0.1:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

定义SseConnectionManager

package com.edevp.webflux;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;
import reactor.core.publisher.FluxSink;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * SSE 连接管理器:管理用户与 SSE 连接的映射
 */
@Component
@Slf4j
public class SseConnectionManager {

    /**
     * 存储用户ID -> SSE 数据流发射器(FluxSink)
     * ConcurrentHashMap 保证线程安全,支持高并发读写
     */
    private final Map<String, FluxSink<ServerSentEvent<String>>> userSinks = new ConcurrentHashMap<>();

    /**
     * 注册用户连接
     * @param userId 用户唯一标识
     * @param sink SSE 数据流发射器(由 WebFlux 生成)
     */
    public void register(String userId, FluxSink<ServerSentEvent<String>> sink) {
        // 注册前先移除旧连接(避免重复连接)
        remove(userId);
        // 注册新连接,并添加断开回调(客户端断开时移除连接)
        userSinks.put(userId, sink);
        sink.onDispose(() -> {
            log.info("用户[{}] SSE 连接断开,移除连接", userId);
            userSinks.remove(userId);
        });
        log.info("用户[{}] SSE 连接注册成功,当前在线数:{}", userId, userSinks.size());
    }

    /**
     * 移除用户连接
     * @param userId 用户唯一标识
     */
    public void remove(String userId) {
        FluxSink<ServerSentEvent<String>> sink = userSinks.remove(userId);
        if (sink != null) {
            sink.complete(); // 主动销毁数据流
            log.info("用户[{}] SSE 连接已移除", userId);
        }
    }

    /**
     * 向单个用户推送消息
     * @param userId 用户唯一标识
     * @param message 推送内容
     */
    public void pushToUser(String userId, String message) {
        FluxSink<ServerSentEvent<String>> sink = userSinks.get(userId);
        if (sink != null && !sink.isCancelled()) {
            try {
                // 构建 SSE 消息(id:消息唯一标识,data:消息内容,retry:重连间隔)
                ServerSentEvent<String> sse = ServerSentEvent.<String>builder()
                        .id(String.valueOf(System.currentTimeMillis())) // 消息ID(客户端可记录,重连时请求未接收的消息)
                        .data(message)
                        .retry(Duration.ofMillis(3000)) // 客户端断开后,3秒后自动重连
                        .build();
                sink.next(sse); // 发送消息
            } catch (Exception e) {
                log.error("向用户[{}]推送消息失败", userId, e);
                remove(userId); // 推送失败,移除无效连接
            }
        }else{
            log.error("用户【{}】不存在",userId);
        }
    }

    /**
     * 广播消息(向所有在线用户推送)
     * @param message 广播内容
     */
    public void broadcast(String message) {
        if (userSinks.isEmpty()) {
            return;
        }
        // 遍历所有连接推送(CopyOnWriteArraySet 避免遍历中修改集合报错)
        new CopyOnWriteArraySet<>(userSinks.entrySet()).forEach(entry -> {
            String userId = entry.getKey();
            FluxSink<ServerSentEvent<String>> sink = entry.getValue();
            if (!sink.isCancelled()) {
                try {
                    ServerSentEvent<String> sse = ServerSentEvent.<String>builder()
                            .id(String.valueOf(System.currentTimeMillis()))
                            .data(message)
                            .retry(Duration.ofMillis(3000))
                            .build();
                    sink.next(sse);
                } catch (Exception e) {
                    log.error("向用户[{}]广播消息失败", userId, e);
                    remove(userId);
                }
            }
        });
        log.info("SSE 广播消息成功,推送用户数:{}", userSinks.size());
    }

    /**
     * 获取当前在线用户数
     */
    public int getOnlineCount() {
        return userSinks.size();
    }
}

定义SseController

package com.edevp.webflux;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Duration;

/**
 * SSE 控制器:暴露 HTTP 接口供客户端连接和测试推送
 * @author bluee
 */
@RestController
@RequestMapping("/sse")
@RequiredArgsConstructor
public class SseController {

    private final SseConnectionManager connectionManager;

    /**
     * 建立 SSE 连接(核心接口)
     * 1. MediaType.TEXT_EVENT_STREAM:SSE 标准响应类型
     * 2. Flux<ServerSentEvent<String>>:响应式数据流,持续向客户端推送消息
     */
    @GetMapping(value = "/connect/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> connect(@PathVariable String userId) {
        // 创建 Flux 数据流,当客户端订阅时触发回调(注册连接)
        return Flux.<ServerSentEvent<String>>create(sink -> {
                    // 注册用户连接
                    connectionManager.register(userId, sink);
                    // 发送连接成功的欢迎消息
                    ServerSentEvent<String> welcomeSse = ServerSentEvent.<String>builder()
                            .id(String.valueOf(System.currentTimeMillis()))
                            .data("SSE 连接成功,用户ID:" + userId)
                            .build();
                    sink.next(welcomeSse);
                })
                // 心跳机制:每30秒发送一次空消息,避免连接被防火墙/网关断开
                .mergeWith(Flux.interval(Duration.ofSeconds(30))
                        .map(seq -> ServerSentEvent.<String>builder()
                                .id("heartbeat-" + seq)
                                .data("") // 空消息(客户端可忽略)
                                .build()))
                // 超时配置:30分钟无数据推送则断开连接(可选)
                .timeout(Duration.ofMinutes(30));
    }

    /**
     * 向单个用户推送消息(测试接口)
     */
    @PostMapping("/push/{userId}")
    public String pushToUser(@PathVariable String userId, @RequestParam String message) {
        connectionManager.pushToUser(userId, message);
        return "消息推送成功,当前在线数:" + connectionManager.getOnlineCount();
    }

    /**
     * 广播消息(测试接口)
     */
    @PostMapping("/broadcast")
    public String broadcast(@RequestParam String message) {
        connectionManager.broadcast(message);
        return "广播成功,当前在线数:" + connectionManager.getOnlineCount();
    }

    /**
     * 获取在线用户数
     */
    @GetMapping("/onlineCount")
    public int getOnlineCount() {
        return connectionManager.getOnlineCount();
    }
}

定义启动类DemoApplication

package com.edevp.webflux;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author bluee
 */
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

定义application.yml

spring:
  webflux:
    server:
      max-http-header-size: 8KB # 最大请求头大小(默认足够)
      compression:
        enabled: true # 开启响应压缩(减少数据传输量)

  reactor:
    netty:
      http:
        server:
          # Netty  acceptor 线程数(默认 CPU 核心数,无需修改)
          # 工作线程数(默认 CPU 核心数×2,无需修改)
          max-connections: 100000 # 最大并发连接数(关键:设置为 10 万)
          connection-timeout: 60s # 连接超时时间(避免空闲连接占用资源)
          idle-timeout: 300s # 空闲超时时间(5分钟无数据则断开)
        client:
          response-timeout: 60s # 客户端响应超时(可选)

# 日志配置(避免日志打印占用资源)
logging:
  level:
    root: INFO
    org.springframework.web: WARN
    reactor.netty: WARN # Netty 日志级别调高,减少输出

定义index.html

<!DOCTYPE html>
<html>
<head>
    <title>SSE 实时推送测试</title>
    <meta charset="UTF-8">
</head>
<body>
<h1>SSE 消息接收区</h1>
<div id="message"></div>

<script>
    // 用户ID(模拟登录用户,实际应从登录态获取)
    const userId = "user-" + Math.random().toString(36).substr(2, 9);
    console.log("当前用户ID:", userId);

    // 建立 SSE 连接(注意:协议为 http/https,端口与服务端一致)
    const eventSource = new EventSource(`http://localhost:8080/sse/connect/${userId}`);

    // 连接成功回调
    eventSource.onopen = function (e) {
        console.log("SSE 连接建立成功", e);
        appendMessage("✅ 连接建立成功,用户ID:" + userId);
    };

    // 接收消息回调
    eventSource.onmessage = function (e) {
        console.log("收到消息:", e.data);
        if (e.data) { // 忽略心跳空消息
            appendMessage(" " + new Date().toLocaleString() + ":" + e.data);
        }
    };

    // 连接错误回调(自动重连)
    eventSource.onerror = function (e) {
        console.error("SSE 连接错误", e);
        appendMessage("❌ 连接异常,正在重连...");
    };

    // 渲染消息到页面
    function appendMessage(content) {
        const div = document.createElement("div");
        div.style.margin = "8px 0";
        div.style.padding = "8px";
        div.style.borderLeft = "3px solid #2196F3";
        div.style.backgroundColor = "#f5f5f5";
        div.innerText = content;
        document.getElementById("message").appendChild(div);
    }
</script>
</body>
</html>

测试启动客户端

在这里插入图片描述

测试发送单条

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值