SSE的简单使用

近期在项目中出现了一个需求:对话实现打字机模式,所以学了一点sse,记录一下。
具体情况如下:
1、第三方厂商使用SSE向后端(我)提供数据
2、后端(我)再向前端提供数据(使用sse模式)
主要需要实现在于两个点:1、与第三方厂商建立sse连接。2、与前端建立sse连接。

第一步-模拟一个服务商

SpringBoot版本:3.1.5,JDK:21

pom

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.23</version>
        </dependency>

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

服务商代码

import cn.hutool.core.util.RandomUtil;
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 reactor.util.function.Tuple2;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class FluxServerController {
    @GetMapping("/server")
    public Flux<ServerSentEvent<String>> server(){
        String kingdom = "东汉末年,山河动荡,刘汉王朝气数将尽。内有十常侍颠倒黑白,祸乱朝纲。外有张氏兄弟高呼“苍天已死,黄巾当立”的口号,掀起浩大的农民起义";
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
          list.add(RandomUtil.randomString(kingdom, 7));
        }
        Flux<ServerSentEvent<String>> serverSentEventFlux = Flux.fromIterable(list)
                .map(data -> ServerSentEvent.builder(data).id(UUID.randomUUID().toString()).event("msg").build())
                .concatWith(Flux.just(ServerSentEvent.<String>builder().id("end").event("complete").data("数据服务提供商,提供数据结束了").build()));
        Flux<Long> interval = Flux.interval(Duration.ofSeconds(3));
      // 模拟一下3秒返回一条数据
        return Flux.zip(interval, serverSentEventFlux).map(Tuple2::getT2);
    }
}

服务商效果

[图片上传失败...(image-372018-1706339652138)]

第二步-业务代码:对接服务商

SpringBoot:2.7.6;JDK:8

pom

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.23</version>
        </dependency>

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

    </dependencies>

业务代码

@GetMapping("/client")
    public Flux<ServerSentEvent<String>> client(){
        // 1、连接服务商:
        //1.1 创建WebClient
        WebClient client = WebClient.builder()
                .baseUrl("http://localhost:8080/server")
                .build();
        //1.2 发送 POST
        Flux<ServerSentEvent<String>> serverSentEventFlux = client.get()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .retrieve()
                .bodyToFlux(
                        new ParameterizedTypeReference<ServerSentEvent<String>>() {
                        }
                );
        // 2、处理接收数据并返回给前端
        return Flux.<ServerSentEvent<String>>create(sink -> {
            serverSentEventFlux.subscribe(new BaseSubscriber<ServerSentEvent<String>>() {
                @Override
                protected void hookOnSubscribe(Subscription subscription) {
                    // 如果要后端关闭与服务商的连接或者与前端的连接,这里把subscription和sink放到concurrentHashMap。就可以用sink控制与前端的sse关闭,用subscription控制和服务商的sse关闭
                    super.hookOnSubscribe(subscription);
                }

                @Override
                protected void hookOnNext(ServerSentEvent<String> value) {
                    // 这里处理所有的数据信息
                    System.out.println(value);
                    sink.next(ServerSentEvent.builder(value.data()).id(UUID.randomUUID().toString()).event(value.event()).build());
                }

                @Override
                protected void hookOnComplete() {
                    System.out.println("SSE结束了!!");
                    super.hookOnComplete();
                }

                @Override
                protected void hookOnError(Throwable throwable) {
                    super.hookOnError(throwable);
                }

                @Override
                protected void hookOnCancel() {
                    super.hookOnCancel();
                }
            });
        });

    }

在这里可以设置不少东西,我在实际项目中就用到了超时
我用的时候基本就是对hookOnSubscribe、hookOnNext的改写,一个用来存连接到concurrentHashMap中,一个处理服务商的数据。

!!还需要注意的是如果正式环境走的NGINX代理,需要设置NGINX超时时间,我设置的超时时间是大于后端连接服务商的超时时间,来保证连接不会被NGINX关闭。

nginx.conf

location /api/sse/ {
        proxy_pass  http://1.1.1.1:90/;
        proxy_buffering off; # 禁用缓冲,确保实时性
            proxy_set_header Connection ''; # 避免Nginx关闭连接
            proxy_read_timeout 120s; # 增加超时时间,确保长连接
    }

前端(uniapp)

不太懂前端,copy了一份前端连接sse的代码。(亲测可用)

需要npm安装这个:event-source-polyfill
!!!这份前端代码是一个示例和上面代码没有联系

createSSE() {
            let that = this
            // qrId
            let qrId = this.wxLoginParam.qrId
            let source = new EventSourcePolyfill(
                `/api/stream/login?qrId=` + qrId)
            this.eventSource = source
            source.addEventListener('open', (e) => {
                console.log('open', e)
            })
            source.addEventListener('message', (e) => {
                console.log('message', e)
            })
            source.addEventListener('START', (e) => {
                console.log('start', e)
            })
            source.addEventListener('EXPIRE', (e) => {
                let res = JSON.parse(e.data);
                this.$u.toast(res.message);
                this.changeEmailLogin()
                console.log('EXPIRE', e)

                source.close();
            })

            source.addEventListener('error', (e) => {
                console.log('error', e)
                source.close();
            })

            source.addEventListener('end', (e) => {
                console.log('end', e)
            })
            source.addEventListener('SUCCESS', (e) => {
                this.$u.toast('登录成功');
                console.log('SUCCESS', e)
                let res = JSON.parse(e.data);
                console.log(res)
                uni.setStorage({
                    key: 'Wukong-Token',
                    data: res.data
                })
                let redirectUrl = "/pages/sys/book/index"
                // 获取存储的 redirectUrl
                uni.getStorage({
                    key: 'loginRedirect',
                    success: function (res) {
                        // 打印获取到的 redirectUrl
                        console.log(res.data);
                        // 使用 setTimeout 来延迟执行 uni.reLaunch
                        redirectUrl = res.data
                    },
                    fail: function (err) {
                        // 处理获取失败的情况
                        redirectUrl = "/pages/sys/book/index"
                    }
                });
                uni.removeStorage('loginRedirect')
                setTimeout(() => {
                    uni.reLaunch({
                        url: redirectUrl
                    });
                }, 500);
            })

        },
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355

推荐阅读更多精彩内容