SpringBoot整合SSE接口實現(xiàn)實時數(shù)據(jù)推送
一、什么是SSE
SSE(Server-Sent Events) 是一種基于HTTP的服務(wù)器向客戶端單向?qū)崟r推送數(shù)據(jù)的技術(shù)。與WebSocket不同,SSE天然支持斷線重連,且協(xié)議簡單,適用于股票行情、實時日志、消息通知等場景。
二、項目環(huán)境準備
1. 基礎(chǔ)依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 若使用WebFlux方式 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
三、兩種實現(xiàn)方式對比
特性 | 傳統(tǒng)Servlet方式 | WebFlux響應(yīng)式方式 |
---|---|---|
線程模型 | 阻塞IO(線程池) | 非阻塞IO(事件循環(huán)) |
資源消耗 | 較高 | 較低 |
代碼復雜度 | 需手動管理線程 | 聲明式編程 |
適用場景 | 簡單低頻場景 | 高并發(fā)實時場景 |
四、傳統(tǒng)Servlet實現(xiàn)(基于SseEmitter)
1. 控制器實現(xiàn)
@RestController public class SseController { @GetMapping("/sse") public SseEmitter handleSse() { SseEmitter emitter = new SseEmitter(); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); Runnable task = () -> { try { String data = "Time: " + LocalDateTime.now(); emitter.send( SseEmitter.event() .data(data) .id(String.valueOf(System.currentTimeMillis())) ); } catch (IOException e) { emitter.completeWithError(e); executor.shutdown(); } }; // 定時發(fā)送(立即執(zhí)行,每秒一次) executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); // 客戶端斷開處理 emitter.onCompletion(executor::shutdown); emitter.onTimeout(executor::shutdown); return emitter; } }
2. 關(guān)鍵點解析
SseEmitter:核心類,保持長連接
ScheduledExecutorService:定時任務(wù)線程池
事件結(jié)構(gòu):支持設(shè)置id/event/data等字段
資源釋放:通過onCompletion/onTimeout確保線程池關(guān)閉
五、響應(yīng)式實現(xiàn)(基于WebFlux)
1. 控制器實現(xiàn)
@RestController public class SseWebFluxController { @GetMapping(value = "/sse-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<String>> streamEvents() { return Flux.interval(Duration.ofSeconds(1)) .map(sequence -> ServerSentEvent.<String>builder() .id(String.valueOf(sequence)) .event("time-update") .data("SSE from WebFlux - " + LocalDateTime.now()) .build()); } }
2. 核心優(yōu)勢
非阻塞IO:基于Reactor庫實現(xiàn)響應(yīng)式流
自動背壓:處理客戶端消費速度差異
簡潔API:使用Flux流式編程
六、接口測試方法
1. 使用curl測試
curl http://localhost:8080/sse
curl http://localhost:8080/sse-stream
2. 前端示例
const eventSource = new EventSource('/sse'); eventSource.onmessage = (e) => { console.log('Received:', e.data); }; eventSource.addEventListener('time-update', (e) => { console.log('Custom event:', e.data); });
七、生產(chǎn)環(huán)境注意事項
連接管理:設(shè)置合理的超時時間(默認30秒)
錯誤處理:添加onError回調(diào)記錄異常
跨域配置:需要配置CORS
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/sse*") .allowedOrigins("*"); } }
性能監(jiān)控:跟蹤活躍連接數(shù)
八、擴展應(yīng)用場景
實時股票報價推送
系統(tǒng)運行狀態(tài)監(jiān)控
聊天應(yīng)用消息通知
長耗時任務(wù)進度更新
九、總結(jié)
兩種實現(xiàn)方式各有優(yōu)勢:
- 傳統(tǒng)Servlet方式 適合簡單場景,快速實現(xiàn)
- WebFlux方式 更適合高并發(fā)、低延遲需求
建議根據(jù)實際場景選擇,對于新項目推薦使用WebFlux實現(xiàn),能更好地利用系統(tǒng)資源。希望本文能幫助您快速上手SpringBoot中的SSE開發(fā)!
到此這篇關(guān)于SpringBoot整合SSE接口實現(xiàn)實時數(shù)據(jù)推送的文章就介紹到這了,更多相關(guān)SpringBoot SSE實時數(shù)據(jù)推送內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA 如何控制編輯左側(cè)的功能圖標ICON(操作步驟)
很多朋友被idea左側(cè)的圖標不見了這一問題搞的焦頭爛額,不知道該怎么操作,今天小編就交大家如何控制編輯左側(cè)的功能圖標 ICON,文字內(nèi)容不多,主要通過兩張截圖給大家說明,感興趣的朋友一起看看吧2021-05-05SpringBoot項目使用?axis?調(diào)用webservice接口的實踐記錄
這篇文章主要介紹了SpringBoot項目使用?axis?調(diào)用webservice接口,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06