SpringBoot流式响应接口

背景:做AI搜索功能, 需要封装AI提供的一个流式接口, 并且同样以流式接口的的形式给到前端

版本#

  • SpringBoot。2.3.2.RELEASE

依赖#

<dependency>
    <groupId>io.projectreactor.netty</groupId>
    <artifactId>reactor-netty</artifactId>
    <version>0.9.10.RELEASE</version>
</dependency>
  • 依赖reactor-netty是为了使用reactor.netty.http.client.HttpClient调用AI接口

代码#

import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

import java.io.IOException;
import java.time.Duration;

@RestController
@RequestMapping("stream")
public class StreamController {
    
    @GetMapping(value = "/streamFlux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamFlux(Object request) {
        return HttpClient.create().post()
                .uri("")
                .send((req, out) -> out.sendString(Mono.just(JSON.toJSONString(request)))).responseContent().asString()
                // 如果 10 秒内没有任何数据,则超时
                .timeout(Duration.ofSeconds(1)).doOnNext(next -> {
                    System.out.println(next);
                }).doOnComplete(() -> {
                    System.out.println("doOnComplete");
                });
    }
}
  • produces = MediaType.TEXT_EVENT_STREAM_VALUE。会自动在返回中加入前缀data: 和 后缀\n\n
posted @   FynnWang  阅读(239)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-01-11 reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response报错
2022-01-11 SpringBoot : server.tomcat.connection-timeout配置解析
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示