• 【流式传输】使用Spring Boot实现ChatGpt流式传输


    引言

        在ChatGpt火了这么久,他的那种单字单字返回的格式可能让很多朋友感到好奇,在之前我用c#写了一个版本的,同时支持IAsyncEnumerable以及SSE,今天把之前写的Java版本的也发出来,和大家一起学习,有不对的地方,欢迎各位大佬指正。

    Code

        我这边用的是JDK21版本,可以看到下面,我们实现了两种方式一种是WebFlux实现响应式返回,另外一种就是SSE的标准写法,有关SSE,大家可以百度去看看他的一些规则,需要设置一些Header,以及返回的数据格式都有特别的讲究。第一种,我们需要在Pom.xml里面引入WebFlux的包,然后才能在代码使用,

       <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webfluxartifactId>
            dependency>
            <dependency>
    复制代码
    @RestController
    
    @RequestMapping("Hello")
    public class HelloController {
    
        @Autowired
        private RestTemplate template;
        public HelloController() {
    
        }
       private String Appid="408035";
        private String Appsecret="PgZgD80aWLrQUxlhVD452aJl";
        @GetMapping(value = "/GetHello", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public Flux GetHello() {
            return Flux.interval(Duration.ofSeconds(1))
                    .map(sequence -> "Event " + sequence);
        }
        @PreAuthorize()
        @GetMapping(value = "/GetHellos", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
        public void GetHellos(HttpServletResponse response) throws Exception
        {
            if (response.containsHeader("Content-Type"))
            {
                response.setHeader("Content-Type","text/event-stream");
            }
            else
            {
                response.setHeader("Content-Type","text/event-stream");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Connection", "keep-alive");
            }
            String data ="id:"+new Random().nextInt() +" \n" +
                "retry: "+new Random().nextInt(0,100)*30+"\n" +
                "event: message\n" +
                "data: "+new Random().nextInt()+"\n\n";
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(data);
        }
      
    
    }
    复制代码

        下面是我们使用WebFlux实现流式传输的一种方式。

         下面是使用SSE实现流式传输的一种,同时前端代码如下。

    复制代码
    DOCTYPE html>
    <html>
    <head>
        <title>SSE Exampletitle>
        <script>
            var eventSource = new EventSource("http://localhost:5203/WeatherForecast/Posta");  
            eventSource.addEventListener("message", function(event) {
    var a=document.getElementById("aaa");
    a.innerHTML+=""+event.data+"
    " console.log("Received message: " + event.data); }); eventSource.addEventListener("error", function(event) { console.log("Error occurred"); }); script> head> <body> <div id='aaa'>div> body> html>
    复制代码

     

     结束

        以上便是今天的所有内容,使用WebFlux以及原始SSE实现流式传输的效果。

  • 相关阅读:
    【java打包下载zip树形结构】打包的时候在zip里创建文件夹自定义路径
    复习Day10:哈希表part03:41. 缺失的第一个正数、138. 随机链表的复制
    【哈希表完整代码】模拟实现哈希表和unordered_set与unordered_map
    Elasticsearch(ES)中 term与match之间的区别
    正则表示式——6.处理比较复杂的正则表示法
    Docker安装Redis集群失败经历汇总
    避免 PostgreSQL 翻车的关键技巧
    图像超分辨率:优化最近邻插值Super-Resolution by Predicting Offsets
    代码扫描工具选型调研
    01分数规划与图论
  • 原文地址:https://www.cnblogs.com/1996-Chinese-Chen/p/17913287.html