SpringBoot實(shí)現(xiàn)Server-Sent Events(SSE)的使用完整指南
一、引言
在Web應(yīng)用開發(fā)中,實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)推送是一個(gè)常見需求。Server-Sent Events(SSE)是HTML5提供的一種服務(wù)器到客戶端的單向通信技術(shù),允許服務(wù)器主動(dòng)向客戶端推送信息,無需客戶端不斷輪詢。本文將詳細(xì)介紹如何在Spring Boot應(yīng)用中實(shí)現(xiàn)SSE,并提供完整的代碼示例。
二、SSE的優(yōu)勢
- 單向通信:服務(wù)器到客戶端的簡單數(shù)據(jù)流,無需客戶端發(fā)送請求。
- 輕量級:基于HTTP,不需要額外的框架或協(xié)議。
- 實(shí)時(shí)性:服務(wù)器端數(shù)據(jù)更新可以即時(shí)推送到客戶端。
三、SSE的典型使用場景
- 實(shí)時(shí)通知:如郵件提醒、社交動(dòng)態(tài)更新等。
- 實(shí)時(shí)數(shù)據(jù)展示:如股票市場數(shù)據(jù)、實(shí)時(shí)統(tǒng)計(jì)信息等。
- 在線聊天室:服務(wù)器端推送新消息給所有在線用戶。
四、Spring Boot實(shí)現(xiàn)SSE的步驟
- 創(chuàng)建Spring Boot項(xiàng)目
首先,你需要?jiǎng)?chuàng)建一個(gè)Spring Boot項(xiàng)目??梢允褂肧pring Initializr或者任何IDE來創(chuàng)建項(xiàng)目,并添加spring-boot-starter-web依賴。 - 創(chuàng)建SSE端點(diǎn)
在Spring Boot項(xiàng)目中,創(chuàng)建一個(gè)控制器來處理SSE請求。
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@RestController
public class SseController {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
@GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamSseMvc() {
SseEmitter emitter = new SseEmitter();
executor.execute(() -> {
try {
for (int i = 0; i < 10; i++) {
// 模擬數(shù)據(jù)處理
Thread.sleep(1000);
emitter.send("Message " + i);
}
emitter.complete();
} catch (IOException | InterruptedException e) {
emitter.completeWithError(e);
}
});
return emitter;
}
}
在上面的代碼中,我們創(chuàng)建了一個(gè)SseEmitter對象,并通過一個(gè)單獨(dú)的線程定期發(fā)送消息到客戶端。
3. 運(yùn)行Spring Boot應(yīng)用
確保你的Spring Boot應(yīng)用已經(jīng)配置好,并且可以運(yùn)行。啟動(dòng)應(yīng)用后,服務(wù)器將在默認(rèn)的8080端口上監(jiān)聽。
4. 客戶端代碼
在客戶端,你可以使用以下HTML和JavaScript代碼來接收SSE。
<!DOCTYPE html>
<html>
<head>
<title>SSE with Spring Boot</title>
</head>
<body>
<h1>Receiving Server-Sent Events</h1>
<div id="messages"></div>
<script>
var eventSource = new EventSource('/sse');
eventSource.onmessage = function(event) {
var messages = document.getElementById('messages');
var message = document.createElement('div');
message.textContent = 'Message from server: ' + event.data;
messages.appendChild(message);
};
eventSource.onerror = function(event) {
console.error('EventSource failed:', event);
eventSource.close();
};
</script>
</body>
</html>
五、測試
啟動(dòng)Spring Boot應(yīng)用,并在瀏覽器中打開上述HTML文件。你應(yīng)該能夠看到服務(wù)器發(fā)送的消息每隔一秒出現(xiàn)在頁面上。
六、總結(jié)
本文展示了如何在Spring Boot應(yīng)用中實(shí)現(xiàn)SSE,通過簡單的步驟和代碼示例,你可以輕松地在你的Web應(yīng)用中添加實(shí)時(shí)數(shù)據(jù)推送功能。SSE提供了一種簡單而有效的方法來處理實(shí)時(shí)數(shù)據(jù)流,非常適合于需要服務(wù)器主動(dòng)推送信息給客戶端的場景。通過Spring Boot,我們可以快速地集成和部署SSE功能,為用戶提供更好的實(shí)時(shí)體驗(yàn)。
到此這篇關(guān)于SpringBoot實(shí)現(xiàn)Server-Sent Events(SSE)的使用完整指南的文章就介紹到這了,更多相關(guān)SpringBoot Server-Sent Events(SSE)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot整合websocket后啟動(dòng)報(bào)錯(cuò)(javax.websocket.server.ServerContainer not available)
- SpringBoot服務(wù)設(shè)置禁止server.point端口的使用
- springboot中server.ssl.key-store配置路徑的問題小結(jié)
- 使用Java和SpringBoot實(shí)現(xiàn)服務(wù)器發(fā)送事件(Server-Sent Events)
- SpringBoot中的server.context-path的實(shí)現(xiàn)
- SpringBoot開啟server:compression:enabled(Illegal character ((CTRL-CHAR, code 31)))的問題解決
相關(guān)文章
基于SpringBoot + Android實(shí)現(xiàn)登錄功能
在移動(dòng)互聯(lián)網(wǎng)的今天,許多應(yīng)用需要通過移動(dòng)端實(shí)現(xiàn)與服務(wù)器的交互功能,其中登錄是最常見且基礎(chǔ)的一種功能,本篇博客將詳細(xì)介紹如何使用 Spring Boot 和 Android 實(shí)現(xiàn)一個(gè)完整的登錄功能,需要的朋友可以參考下2024-11-11
解決Mybatis?plus實(shí)體類屬性與表字段不一致的問題
這篇文章主要介紹了Mybatis?plus實(shí)體類屬性與表字段不一致解決方法,文末給大家提到了Mybatis-plus中數(shù)據(jù)庫表名和表字段名的相關(guān)知識,需要的朋友可以參考下2022-07-07
Spring事務(wù)管理只對出現(xiàn)運(yùn)行期異常進(jìn)行回滾
Spring的事務(wù)管理默認(rèn)只對出現(xiàn)運(yùn)行期異常(java.lang.RuntimeException及其子類)進(jìn)行回滾,需要了解更多Spring事務(wù)方面的知識,可詳看本文2012-11-11

