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

引言

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

Code

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

   <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-webflux</artifactId>         </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<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: messagen" +             "data: "+new Random().nextInt()+"nn";         response.setCharacterEncoding("UTF-8");         response.getWriter().write(data);     }     }

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

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

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

<!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>

 

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

 结束

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

发表评论

评论已关闭。

相关文章