实时数据推送:Spring Boot 中两种 SSE 实战方案

在 Web 开发中,实时数据交互变得越来越普遍。无论是股票价格的波动、比赛比分的更新,还是聊天消息的传递,都需要服务器能够及时地将数据推送给客户端。传统的 HTTP 请求-响应模式在处理这类需求时显得力不从心,而服务器推送事件(Server-Sent Events,SSE)为我们提供了一种轻量级且高效的解决方案。

本文将介绍两种基于 Spring Boot 实现 SSE 的方案,并结合代码示例,帮助你快速掌握实时数据推送的技巧。

SSE:轻量级实时数据传输方案

SSE 是一种基于 HTTP 的服务器推送技术,它允许服务器在事件发生时主动将数据推送给客户端,无需客户端不断发起请求。SSE 使用简单的文本格式传输数据,并利用浏览器原生的 EventSource 对象进行处理。

SSE 的优势:

  • 简单易用: 基于 HTTP 协议,无需额外学习成本。
  • 轻量级: 数据格式简单,传输效率高。
  • 浏览器兼容性好: 大多数现代浏览器都支持 SSE。

方案一:Spring WebFlux(或 Reactor ) + SSE,打造响应式实时数据流

Spring WebFlux 是 Spring Framework 5.0 推出的响应式 Web 框架,它基于 Reactor 库,支持异步非阻塞的编程模型,能够高效处理大量并发连接和数据流。

  1. 异步调用 API: 使用 WebClient 或其他异步 HTTP 客户端库异步调用外部 API。
  2. 使用 Flux 或 Mono 处理响应: 使用 Reactor 的 Flux 或 Mono 类型处理异步 API 的响应数据流。
  3. 整合到 SSE 流中: 将 API 响应数据整合到已有的 SSE 流中,或者创建一个新的 SSE 流并将数据推送给前端。

1. 添加依赖:


    org.springframework.boot
    spring-boot-starter-webflux

2. 创建 Controller:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;

@RestController
public class ChatController {

    private final WebClient webClient; // 用于调用外部 API

    public ChatController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://api.example.com").build(); 
    }

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux> streamChatGPTReply(@RequestParam String message) {
        // 使用 WebClient 异步调用外部 API
        return webClient.post()
                .uri("/api/external") 
                .bodyValue(message)
                .retrieve()
                .bodyToFlux(String.class)
                .map(data -> ServerSentEvent.builder()
                        .data(data)
                        .build())
                .delayElements(Duration.ofMillis(100)); // 模拟延迟
    }
}

3. 前端代码示例:




    SSE Chat Demo


    

SSE Chat

方案二:Spring MVC + DeferredResult/Callable,实现异步结果返回

在 Spring MVC 中,我们可以使用 DeferredResult 或 Callable 实现异步结果返回,从而实现服务器推送。

  1. 创建一个 DeferredResult 或 Callable 对象: 这两个对象都允许异步返回结果。
  2. 启动一个新线程调用 API: 在新线程中调用外部 API,避免阻塞主线程。
  3. 设置 DeferredResult 的结果或返回 Callable 的值: 在 API 调用完成后,设置 DeferredResult 的结果或返回 Callable 的值,Spring 会自动将结果发送给前端。

1. 使用 DeferredResult:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class DeferredResultController {

    @GetMapping(value = "/deferred", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public DeferredResult handleRequest(@RequestParam String message) {
        DeferredResult result = new DeferredResult<>();

        new Thread(() -> {
            // 模拟耗时操作,例如调用外部 API
            String apiResponse = callExternalAPI(message);
            // 设置 DeferredResult 的结果
            result.setResult(apiResponse);
        }).start();

        return result;
    }

    private String callExternalAPI(String message) {
        // 模拟调用外部 API 并返回结果
        return "External API response for: " + message;
    }
}

2. 使用 Callable:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Callable;

@RestController
public class CallableController {

    @GetMapping(value = "/callable", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Callable handleRequest(@RequestParam String message) {
        return () -> {
            // 模拟耗时操作,例如调用外部 API
            String apiResponse = callExternalAPI(message);
            return apiResponse;
        };
    }

    private String callExternalAPI(String message) {
        // 模拟调用外部 API 并返回结果
        return "External API response for: " + message;
    }
}

前端代码同上

总结

本文介绍了两种基于 Spring Boot 实现 SSE 的方案:

  • Spring WebFlux + SSE: 更适合处理大量并发连接和数据流的场景,代码简洁优雅,更符合响应式编程的思想。
  • Spring MVC + DeferredResult/Callable: 更适合处理单个请求的异步结果返回,代码相对简单,但可扩展性有限。

你可以根据具体的业务需求选择合适的方案来实现实时数据推送功能。无论选择哪种方案,SSE 都为我们提供了一种轻量级、高效、易于实现的实时数据传输方案,可以帮助我们构建更加优秀的用户体验.

你可能感兴趣的:(java,SpringBoot,html5,前端,服务器,spring,http,交互)