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

15 篇文章 0 订阅
3 篇文章 0 订阅

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

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

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

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

SSE 的优势:

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

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

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

1. 添加依赖:

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

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<ServerSentEvent<String>> streamChatGPTReply(@RequestParam String message) {
        // 使用 WebClient 异步调用外部 API
        return webClient.post()
                .uri("/api/external") 
                .bodyValue(message)
                .retrieve()
                .bodyToFlux(String.class)
                .map(data -> ServerSentEvent.<String>builder()
                        .data(data)
                        .build())
                .delayElements(Duration.ofMillis(100)); // 模拟延迟
    }
}

3. 前端代码示例:

<!DOCTYPE html>
<html>
<head>
    <title>SSE Chat Demo</title>
</head>
<body>
    <h1>SSE Chat</h1>
    <div id="messages"></div>
    <input type="text" id="message" placeholder="Enter message">
    <button onclick="sendMessage()">Send</button>

    <script>
        const eventSource = new EventSource('/stream?message=Hello'); // 连接到 SSE 接口

        eventSource.onmessage = (event) => {
            document.getElementById('messages').innerHTML += event.data + '<br>'; // 显示接收到的消息
        };

        eventSource.onerror = (error) => {

             console.error('SSE 连接错误:', error);

             eventSource.close();

        };

        function sendMessage() {
            const message = document.getElementById('message').value;
            // 发送消息到服务器,这里仅作示例,实际应用中可能需要调用其他 API
        }
    </script>
</body>
</html>

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

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

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<String> handleRequest(@RequestParam String message) {
        DeferredResult<String> 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<String> 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 都为我们提供了一种轻量级、高效、易于实现的实时数据传输方案,可以帮助我们构建更加优秀的用户体验.

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值