前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【流式传输】使用Spring Boot实现ChatGpt流式传输

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

作者头像
陈显达
发布2023-12-20 09:17:07
9470
发布2023-12-20 09:17:07
举报

引言

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

Code

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

代码语言:javascript
复制
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
代码语言:javascript
复制
@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<String> 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实现流式传输的一种,同时前端代码如下。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
    <title>SSE Example</title>
    <script>
        var eventSource = new EventSource("http://localhost:5203/WeatherForecast/Posta");  
        eventSource.addEventListener("message", function(event) {
var a=document.getElementById("aaa");
a.innerHTML+="<a>"+event.data+"</a><br>"
            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实现流式传输的效果。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-12-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 引言
  • Code
  •  结束
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档