最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot實(shí)現(xiàn)SSE實(shí)時推送實(shí)戰(zhàn)示例

 更新時間:2025年08月11日 11:52:15   作者:Vesper63  
本文給大家介紹基于SpringBoot實(shí)現(xiàn)SSE示例,包括創(chuàng)建項目、SSE控制器處理連接與消息推送、跨域配置、客戶端使用EventSource訂閱,以及動態(tài)推送和WebFlux擴(kuò)展,感興趣的朋友跟隨小編一起看看吧

以下是一個完整的基于 Spring Boot 的 Server-Sent Events (SSE) 示例,包括服務(wù)端和客戶端的實(shí)現(xiàn)。

一、服務(wù)端實(shí)現(xiàn)

1. 創(chuàng)建 Spring Boot 項目

首先,創(chuàng)建一個基本的 Spring Boot 項目,并添加 spring-boot-starter-web 依賴。在 pom.xml 中添加以下內(nèi)容:

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

2. 創(chuàng)建 SSE 控制器

創(chuàng)建一個控制器來處理 SSE 連接并推送實(shí)時消息。

SseController.java

package com.example.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;
import java.util.concurrent.TimeUnit;
@RestController
public class SseController {
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    @GetMapping("/sse")
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter();
        executorService.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    emitter.send("Message " + i, MediaType.TEXT_PLAIN);
                    TimeUnit.SECONDS.sleep(1);
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
}

3. 配置跨域(可選)

如果前端和后端運(yùn)行在不同端口上,需要配置跨域。

CorsConfig.java

package com.example.sse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

二、客戶端實(shí)現(xiàn)

在前端頁面中,使用 EventSource 來訂閱 SSE。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Example</title>
</head>
<body>
    <h1>Server-Sent Events Example</h1>
    <div id="events"></div>
    <script>
        const eventSource = new EventSource('/sse');
        eventSource.onmessage = function(event) {
            const newElement = document.createElement("div");
            newElement.innerHTML = "Message: " + event.data;
            document.getElementById("events").appendChild(newElement);
        };
        eventSource.onerror = function(event) {
            eventSource.close();
            alert("EventSource failed: " + event);
        };
    </script>
</body>
</html>

三、運(yùn)行和測試

  1. 啟動 Spring Boot 應(yīng)用。
  2. 在瀏覽器中訪問 http://localhost:8080,即可看到服務(wù)端每秒推送的消息。

四、擴(kuò)展功能

1. 動態(tài)推送消息

可以通過維護(hù)一個 SseEmitter 的映射來動態(tài)推送消息。

SseController.java(動態(tài)推送版本)

package com.example.sse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
public class SseController {
    private final Map<String, SseEmitter> emitterMap = new ConcurrentHashMap<>();
    @GetMapping("/sse/{userId}")
    public SseEmitter connect(@PathVariable String userId) {
        SseEmitter emitter = new SseEmitter();
        emitterMap.put(userId, emitter);
        emitter.onCompletion(() -> emitterMap.remove(userId));
        emitter.onTimeout(() -> emitterMap.remove(userId));
        emitter.onError(e -> emitterMap.remove(userId));
        return emitter;
    }
    @GetMapping("/push/{userId}")
    public void push(@PathVariable String userId, @RequestParam String message) {
        SseEmitter emitter = emitterMap.get(userId);
        if (emitter != null) {
            try {
                emitter.send(message);
            } catch (IOException e) {
                emitter.completeWithError(e);
                emitterMap.remove(userId);
            }
        }
    }
}

2. 使用 WebFlux 實(shí)現(xiàn) SSE

如果需要更高效的響應(yīng)式編程支持,可以使用 Spring WebFlux。

SseController.java(WebFlux 版本)

package com.example.sse;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
@RestController
public class SseController {
    @GetMapping("/sse/stream")
    public Flux<ServerSentEvent<String>> streamSse() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> ServerSentEvent.<String>builder()
                        .id(String.valueOf(sequence))
                        .event("periodic-event")
                        .data("Current time: " + java.time.LocalTime.now())
                        .build());
    }
}

通過以上步驟,你可以實(shí)現(xiàn)一個完整的基于 Spring Boot 的 SSE 應(yīng)用。

到此這篇關(guān)于Spring Boot實(shí)現(xiàn)SSE實(shí)時推送實(shí)戰(zhàn)示例的文章就介紹到這了,更多相關(guān)springboot sse實(shí)時推送內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java Swing組件單選框JRadioButton用法示例

    Java Swing組件單選框JRadioButton用法示例

    這篇文章主要介紹了Java Swing組件單選框JRadioButton用法,結(jié)合具體實(shí)例形式分析了Swing單選框JRadioButton的使用方法及相關(guān)操作注意事項,需要的朋友可以參考下
    2017-11-11
  • mybatis實(shí)現(xiàn)mapper配置并查詢數(shù)據(jù)的思路詳解

    mybatis實(shí)現(xiàn)mapper配置并查詢數(shù)據(jù)的思路詳解

    這篇文章主要介紹了mybatis實(shí)現(xiàn)mapper配置并查詢數(shù)據(jù),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-04-04
  • Java中byte輸出write到文件的實(shí)現(xiàn)方法講解

    Java中byte輸出write到文件的實(shí)現(xiàn)方法講解

    今天小編就為大家分享一篇關(guān)于Java中byte輸出write到文件的實(shí)現(xiàn)方法講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • java.lang.IncompatibleClassChangeError異常的問題解決

    java.lang.IncompatibleClassChangeError異常的問題解決

    本文主要介紹了java.lang.IncompatibleClassChangeError異常的問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-06-06
  • 深入解析Java的設(shè)計模式編程中單例模式的使用

    深入解析Java的設(shè)計模式編程中單例模式的使用

    這篇文章主要介紹了深入解析Java的設(shè)計模式編程中單例模式的使用,一般來說將單例模式分為餓漢式單例和懶漢式單例,需要的朋友可以參考下
    2016-02-02
  • Java設(shè)計模式之模板方法模式

    Java設(shè)計模式之模板方法模式

    這篇文章介紹了Java設(shè)計模式之模板方法模式,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • java實(shí)現(xiàn)微信公眾平臺發(fā)送模板消息的示例代碼

    java實(shí)現(xiàn)微信公眾平臺發(fā)送模板消息的示例代碼

    這篇文章主要介紹了java實(shí)現(xiàn)微信公眾平臺發(fā)送模板消息的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • elasticsearch中的mapping簡介(最新整理)

    elasticsearch中的mapping簡介(最新整理)

    Mapping 也稱之為映射,定義了 ES 的索引結(jié)構(gòu)、字段類型、分詞器等屬性,是索引必不可少的組成部分,這篇文章主要介紹了elasticsearch中的mapping簡介,需要的朋友可以參考下
    2025-06-06
  • 詳解大數(shù)據(jù)處理引擎Flink內(nèi)存管理

    詳解大數(shù)據(jù)處理引擎Flink內(nèi)存管理

    Flink是jvm之上的大數(shù)據(jù)處理引擎,jvm存在java對象存儲密度低、full gc時消耗性能,gc存在stw的問題,同時omm時會影響穩(wěn)定性。針對頻繁序列化和反序列化問題flink使用堆內(nèi)堆外內(nèi)存可以直接在一些場景下操作二進(jìn)制數(shù)據(jù),減少序列化反序列化消耗。本文帶你詳細(xì)理解其原理。
    2021-05-05
  • IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測有用永久激活)

    IntelliJ?IDEA?2022.2.3最新激活圖文教程(親測有用永久激活)

    今天給大家分享一個?IDEA?2022.2.3?的激活破解教程,全文通過文字+圖片的方式講解,手把手教你如何激活破解?IDEA,?只需要幾分鐘即可搞定,對idea2022.2.3激活碼感興趣的朋友跟隨小編一起看看吧
    2022-11-11

最新評論

十堰市| 安宁市| 电白县| 青浦区| 元朗区| 集贤县| 舒城县| 巍山| 秦皇岛市| 贵溪市| 甘南县| 彭山县| 泉州市| 墨脱县| 深州市| 墨玉县| 固镇县| 临沂市| 德令哈市| 浦城县| 张家界市| 凭祥市| 六盘水市| 祁连县| 华阴市| 肇州县| 张家口市| 厦门市| 安国市| 乌恰县| 安阳市| 哈尔滨市| 习水县| 綦江县| 民权县| 桂阳县| 怀化市| 边坝县| 泰顺县| 北安市| 乐山市|