【流式传输】使用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: message\n" +
"data: "+new Random().nextInt()+"\n\n";
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
}
} 下面是我们使用WebFlux实现流式传输的一种方式。
https://img2023.cnblogs.com/blog/2086997/202312/2086997-20231219111511845-752854651.gif
下面是使用SSE实现流式传输的一种,同时前端代码如下。
<!DOCTYPE html>
<html>
<head>
<title>SSE Example</title>
</head>
<body>
</body>
</html>
https://img2023.cnblogs.com/blog/2086997/202312/2086997-20231219112003335-2016486903.gif
结束
以上便是今天的所有内容,使用WebFlux以及原始SSE实现流式传输的效果。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]