建设网站的基本工作流程,淘宝推广引流方法有哪些,wordpress 外部视频,百度合伙人答题兼职赚钱在 Web 开发中#xff0c;实时数据交互变得越来越普遍。无论是股票价格的波动、比赛比分的更新#xff0c;还是聊天消息的传递#xff0c;都需要服务器能够及时地将数据推送给客户端。传统的 HTTP 请求-响应模式在处理这类需求时显得力不从心#xff0c;而服务器推送事件实时数据交互变得越来越普遍。无论是股票价格的波动、比赛比分的更新还是聊天消息的传递都需要服务器能够及时地将数据推送给客户端。传统的 HTTP 请求-响应模式在处理这类需求时显得力不从心而服务器推送事件Server-Sent EventsSSE为我们提供了一种轻量级且高效的解决方案。
本文将介绍两种基于 Spring Boot 实现 SSE 的方案并结合代码示例帮助你快速掌握实时数据推送的技巧。
SSE轻量级实时数据传输方案
SSE 是一种基于 HTTP 的服务器推送技术它允许服务器在事件发生时主动将数据推送给客户端无需客户端不断发起请求。SSE 使用简单的文本格式传输数据并利用浏览器原生的 EventSource 对象进行处理。
SSE 的优势
简单易用: 基于 HTTP 协议无需额外学习成本。轻量级: 数据格式简单传输效率高。浏览器兼容性好: 大多数现代浏览器都支持 SSE。
方案一Spring WebFlux(或 Reactor ) SSE打造响应式实时数据流
Spring WebFlux 是 Spring Framework 5.0 推出的响应式 Web 框架它基于 Reactor 库支持异步非阻塞的编程模型能够高效处理大量并发连接和数据流。
异步调用 API: 使用 WebClient 或其他异步 HTTP 客户端库异步调用外部 API。使用 Flux 或 Mono 处理响应: 使用 Reactor 的 Flux 或 Mono 类型处理异步 API 的响应数据流。整合到 SSE 流中: 将 API 响应数据整合到已有的 SSE 流中或者创建一个新的 SSE 流并将数据推送给前端。
1. 添加依赖:
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-webflux/artifactId
/dependency2. 创建 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 FluxServerSentEventString streamChatGPTReply(RequestParam String message) {// 使用 WebClient 异步调用外部 APIreturn webClient.post().uri(/api/external) .bodyValue(message).retrieve().bodyToFlux(String.class).map(data - ServerSentEvent.Stringbuilder().data(data).build()).delayElements(Duration.ofMillis(100)); // 模拟延迟}
}3. 前端代码示例:
!DOCTYPE html
html
headtitleSSE Chat Demo/title
/head
bodyh1SSE Chat/h1div idmessages/divinput typetext idmessage placeholderEnter messagebutton onclicksendMessage()Send/buttonscriptconst eventSource new EventSource(/stream?messageHello); // 连接到 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 实现异步结果返回从而实现服务器推送。
创建一个 DeferredResult 或 Callable 对象: 这两个对象都允许异步返回结果。启动一个新线程调用 API: 在新线程中调用外部 API避免阻塞主线程。设置 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 DeferredResultString handleRequest(RequestParam String message) {DeferredResultString 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 CallableString 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 都为我们提供了一种轻量级、高效、易于实现的实时数据传输方案可以帮助我们构建更加优秀的用户体验.