SSE接口的几种实现方式

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

我会在本章介绍SSE接口的几种实现方式,包括webflux和spring mvc,以及使用几种方法调用sse接口的方法。


一、sse是什么?

SSE 接口" 通常指的是 Server-Sent Events(SSE)接口。Server-Sent Events 是一种用于在客户端和服务器之间实现单向实时通信的 web 技术。它允许服务器向客户端推送事件,而客户端通过简单的 JavaScript 代码监听这些事件。

SSE 主要用于实现服务器向客户端的实时更新,例如推送新闻、实时股票报价、即时通讯等场景。与其他实时通信技术(如 WebSocket)相比,SSE 是一种简单的、基于 HTTP 的轻量级解决方案,适用于一些场景下不需要双向通信的应用。

二、webFlux和Spring MVC

1. 响应式编程模型:

WebFlux:

WebFlux 是基于响应式编程模型的框架,支持反应式流和非阻塞 I/O。

使用 Flux 或 Mono 类型来表示 SSE 数据流。

Spring MVC:

Spring MVC 是传统的 Servlet 模型,采用同步阻塞的方式处理请求和响应。

在 Spring MVC 中,使用 SseEmitter 类来处理 SSE 数据流。

2. 数据流类型:

WebFlux:

使用 Flux 或 Mono 类型,其中 ServerSentEvent 对象包装 SSE 数据。

适用于响应式、非阻塞的场景。

Spring MVC:

使用 SseEmitter 类,可以发送任意类型的数据,不仅仅是 ServerSentEvent。

SseEmitter 提供更大的灵活性,可以发送任何类型的数据。

3. 框架整合:

WebFlux:

WebFlux 与整个响应式编程框架集成,更适用于构建响应式、非阻塞的应用程序。

Spring MVC:

Spring MVC

传统的 Servlet 模型,适用于同步处理请求的应用程序。

4. 代码示例:

使用 WebFlux 处理 SSE:
java 复制代码
@RestController
@RequestMapping("/api")
public class SSEController {

    @GetMapping("/stream")
    public Flux<ServerSentEvent<String>> handleStream() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(index -> ServerSentEvent.builder("Data: " + index).build());
    }
}
Spring MVC 处理 SSE::
java 复制代码
@RestController
@RequestMapping("/api")
public class SSEController {

    @GetMapping("/stream")
    public SseEmitter handleStream() {
        SseEmitter emitter = new SseEmitter();
        // 设置 SSEEmitter 的处理逻辑
        // ...
         emitter.send(data);
        return emitter;
    }
}

三.webflux和okhttp调用sse的区别

webflux

c 复制代码
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

public class WebClientSSEExample {

    public static void main(String[] args) {
        WebClient webClient = WebClient.create("http://your-server");

        Flux<String> sseFlux = webClient.get()
                .uri("/api/stream")
                .retrieve()
                .bodyToFlux(String.class);

        sseFlux.subscribe(eventData -> {
            System.out.println("Received Event: " + eventData);
        });
    }
}

okhttp

java 复制代码
import okhttp3.*;
import okhttp3.Request.Builder;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

public class OkHttpSSEExample {

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Builder().url("http://your-server/api/stream").build();

        EventSourceListener listener = new EventSourceListener() {
            @Override
            public void onEvent(String id, String type, String data) {
                System.out.println("Received Event: " + data);
            }

            @Override
            public void onFailure(Exception e, Response response) {
                e.printStackTrace();
            }
        };

        EventSource eventSource = new EventSource(request, listener);
        eventSource.start();
    }
}

四.同步获取完整完整数据

c 复制代码
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

public class WebClientSSEExample {

    public static void main(String[] args) {
        WebClient webClient = WebClient.create("http://your-server");

        Flux<String> sseFlux = webClient.get()
                .uri("/api/stream")
                .retrieve()
                .bodyToFlux(String.class);
		String last = sseFlux.blockLast();
    }
}

相关推荐
jinanwuhuaguo36 分钟前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
RuoyiOffice42 分钟前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
xmjd msup1 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
952362 小时前
SpringBoot统一功能处理
java·spring boot·后端
Lyyaoo.2 小时前
优惠券秒杀业务分析
java·开发语言
消失的旧时光-19432 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
勿忘初心12212 小时前
Java 国密 SM4 加密工具类实战(Hutool + BouncyCastle)|企业级数据加密 + 兼容 JDK8
java·数据安全·数据加密·后端开发·企业级开发·国密 sm4
庞轩px2 小时前
第8篇:原子类与CAS底层原理——无锁并发的实现
java·cas·乐观锁·aba·无锁编程·自旋
rleS IONS2 小时前
SpringBoot中自定义Starter
java·spring boot·后端
苍煜3 小时前
慢SQL优化实战教学
java·数据库·sql