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();
    }
}

相关推荐
极小狐1 天前
极狐GitLab 18.5 正式发布,更新 Maven 虚拟仓库 UI(Beta)、全新个人主页、实例级合规与安全策略管理 以及 DAST 认证脚本 等
java·gitlab·maven
王元_SmallA1 天前
【玩转全栈】----Django基本配置和介绍
java·后端
LiuYaoheng1 天前
【Android】Drawable 基础
android·java
AlianNiew1 天前
从源码到实战:用 Java 打造“限时+防重放”的文件安全预览链接
java·后端
星梦清河1 天前
Redis(四):缓存击穿及其解决方案(SpringBoot+mybatis-plus)
spring boot·redis·缓存
null or notnull1 天前
java服务器空间不够时:将多个服务器的文件存放至同一个服务器上(使用映射器的办法)
java·运维·服务器·java-ee
FAFU_kyp1 天前
WebMvcConfig 和 WebSecurityConfig 详解
spring boot·java-ee
代码栈上的思考1 天前
JVM中内存管理的策略
java·jvm
往事随风去1 天前
虚拟线程在Spring Boot中的正确使用方式
spring boot
YoungP1 天前
【Effective Java 条目二】-- 当构造器参数较多时考虑使用生成器
java