java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot   Spring WebFlux SSE

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

作者:Joyous

Spring Boot 3.4.3 结合Spring WebFlux实现SSE 功能,为实时数据推送提供了优雅的解决方案,通过本文的步骤,你可以快速搭建一个基于事件驱动的后端服务,满足实时通知或监控等需求,感兴趣的朋友一起看看吧

在现代 Web 应用开发中,实时数据推送已成为许多业务场景的核心需求,例如实时通知、股票价格更新或在线聊天等。传统的轮询方式效率低下,而 SSE(Server-Sent Events,服务器推送事件)作为 HTML5 提供的一种轻量级技术,能够通过单向长连接实现服务器到客户端的实时数据推送。Spring Boot 3.4.3 结合 Spring WebFlux,为开发者提供了响应式编程能力,使得实现 SSE 功能更加简单高效。本文将详细介绍如何在 Spring Boot 3.4.3 中基于 Spring WebFlux 实现 SSE 功能,并提供完整的代码示例,助你在企业级应用中快速落地实时推送需求。

1. SSE 简介

1.1 什么是 SSE?

SSE(Server-Sent Events)是一种基于 HTTP 协议的服务器推送技术,允许服务器主动向客户端发送数据。客户端通过建立长连接接收服务器推送的事件流,适用于需要实时更新的场景。与 WebSocket 相比,SSE 是单向通信(仅服务器到客户端),实现更简单,且浏览器原生支持。

1.2 SSE 的优点

1.3 适用场景

2. Spring WebFlux 简介

Spring WebFlux 是 Spring 5 引入的响应式 Web 框架,与传统的 Spring MVC 不同,它基于 Reactor 项目,支持异步非阻塞的编程模型。Spring Boot 3.4.3 默认集成了 Spring WebFlux,使得开发者可以轻松构建高并发、事件驱动的应用。结合 SSE,WebFlux 的 Flux 数据流非常适合处理实时推送需求。

3. 项目实战

以下是基于 Spring Boot 3.4.3 和 Spring WebFlux 实现 SSE 功能的完整步骤。

3.1 添加 Maven 依赖

pom.xml 中添加 Spring WebFlux 的依赖:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.3</version>
    </parent>
    <artifactId>springboot-sse</artifactId>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
    </dependencies>
</project>

说明:

3.2 创建 SSE 控制器

创建一个控制器,用于推送事件流:

package cn.joyous.sse.controller;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
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.util.concurrent.atomic.AtomicInteger;
/**
 */
@RestController
public class SSEController {
    // 定义一个计数器,用于模拟数据变化
    private final AtomicInteger counter = new AtomicInteger(0);
    @GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Integer>> streamEvents() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(seq -> ServerSentEvent.<Integer>builder()
                        .id(String.valueOf(seq))
                        .event("message")
                        .data(counter.incrementAndGet())
                        .build());
    }
}

代码说明:

3.3 前端页面示例

创建一个简单的 HTML 页面,用于接收 SSE 数据:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>SSE Demo</title>
</head>
<body>
    <h1>SSE 数据推送</h1>
    <div id="result"></div>
    <script>
        const eventSource = new EventSource("http://localhost:8080/sse");
        eventSource.onmessage = function(event) {
            document.getElementById("result").innerText += "收到数据: " + event.data + "\n";
        };
        eventSource.onerror = function() {
            console.log("SSE 连接失败");
            eventSource.close();
        };
    </script>
</body>
</html>

保存为 sse.html,放置在 src/main/resources/static 目录下。

3.4 启动与测试

id: 0
event: message
data: 1
id: 1
event: message
data: 2

4. 进阶功能(可选)

自定义事件类型
修改控制器支持多种事件:

@GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamEvents() {
    return Flux.interval(Duration.ofSeconds(1))
            .map(seq -> ServerSentEvent.<String>builder()
                    .id(String.valueOf(seq))
                    .event(seq % 2 == 0 ? "even" : "odd")
                    .data("Count: " + counter.incrementAndGet())
                    .build());
}

动态推送特定用户
使用 Map 存储用户连接:

private final Map<String, Sinks.Many<String>> userSinks = new ConcurrentHashMap<>();
@GetMapping("/sse/{userId}")
public Flux<ServerSentEvent<String>> userStream(@PathVariable String userId) {
    Sinks.Many<String> sink = userSinks.computeIfAbsent(userId, k -> Sinks.many().multicast().onBackpressureBuffer());
    return sink.asFlux().map(data -> ServerSentEvent.builder().data(data).build());
}

异常处理
添加错误重连逻辑:

return Flux.interval(Duration.ofSeconds(1))
        .map(seq -> ServerSentEvent.<Integer>builder().data(counter.incrementAndGet()).build())
        .onErrorResume(e -> Flux.just(ServerSentEvent.builder().data("Error: " + e.getMessage()).build()));

5. 总结

Spring Boot 3.4.3 结合 Spring WebFlux 实现 SSE 功能,为实时数据推送提供了优雅的解决方案。通过本文的步骤,你可以快速搭建一个基于事件驱动的后端服务,满足实时通知或监控等需求。相比 WebSocket,SSE 更轻量且易于集成,适合单向推送场景。

到此这篇关于Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能的文章就介绍到这了,更多相关Spring Boot   Spring WebFlux SSE内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文