当前位置: 首页 > news >正文

实时数据推送: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. 添加依赖:

<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; // 用于调用外部 APIpublic 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 异步调用外部 APIreturn 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 或 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<String> handleRequest(@RequestParam String message) {DeferredResult<String> result = new DeferredResult<>();new Thread(() -> {// 模拟耗时操作,例如调用外部 APIString 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 () -> {// 模拟耗时操作,例如调用外部 APIString 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 都为我们提供了一种轻量级、高效、易于实现的实时数据传输方案,可以帮助我们构建更加优秀的用户体验.

http://www.lryc.cn/news/426218.html

相关文章:

  • 数据守护者:SQL一致性检查的艺术与实践
  • jenkins配置+vue打包多环境切换
  • idea和jdk的安装教程
  • HTML静态网页成品作业(HTML+CSS)——电影网首页网页设计制作(1个页面)
  • 大数据系列之:Flink Doris Connector,实时同步数据到Doris数据库
  • LabVIEW VI 多语言动态加载与运行的实现
  • Unity引擎基础知识
  • 练习题- 探索正则表达式对象和对象匹配
  • Java集合提升
  • uniapp 微信小程序生成水印图片
  • ElasticSearch相关知识点
  • css 文字图片居中及网格布局
  • 解决ImportError: DLL load failed while importing _rust: 找不到指定的程序
  • 集合-List去重
  • ST-LINK USB communication error 非常有效的解决方法
  • 探索CSS的:future-link伪类:选择指向未来文档的链接
  • 【C++】序列与关联容器(三)map与multimap容器
  • ActiveMQ、RabbitMQ、Kafka、RocketMQ在优先级队列、延迟队列、死信队列、重试队列、消费模式、广播模式的区别
  • 首款会员制区块链 Geist 介绍
  • CANoe软件中Trace窗口的筛选栏标题不显示(空白)的解决方法
  • 日期类代码实现-C++
  • 【问题记录+总结】VS Code Tex Live 2024 Latex Workshop Springer模板----更新ing
  • Linux运维_Bash脚本_源码安装Go-1.21.11
  • ShareSDK Twitter
  • word2vec 如何用多个词表示一个句子
  • IDEA中查看接口的所有实现类和具体实现类
  • DLL的导出和调用
  • vscode中调试cuda kernel
  • SQL的连接查询与pandas的对应关系
  • 【JS】中断和恢复任务序列