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

相关推荐
哎呦没30 分钟前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
编程、小哥哥1 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程2 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇2 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码2 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
郭二哈3 小时前
C++——模板进阶、继承
java·服务器·c++
A尘埃3 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23073 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
沉登c3 小时前
幂等性接口实现
java·rpc
代码之光_19803 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端