SpringBoot+WebFlux通过流式响应实现类似ChatGPT的打字机效果

突然间想用Java实现一下像ChatGPT一样的打字机输出效果,但是网上搜了相关教程感觉都不够满意。
这里贴一下自己的实现,为中文互联网做一点小小的贡献

最主要的一点就是响应的Content-Type设置为MediaType.TEXT_EVENT_STREAM_VALUE


实现效果如下

引入WebFlux和Hutool依赖

代码如下


import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

/**
 * @author Juyss
 * @version 1.0
 * @description: TODO
 * @date 2024/6/11 20:52
 */
@RestController
@RequestMapping("/chat")
public class ChatController {

    @GetMapping(value = "/webflux",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chatWebFlux(@RequestParam int delay) {
        String string = ResourceUtil.readUtf8Str("classpath:static/test.txt");
        String[] stringArray = StrUtil.split(string, 1);
        return Flux.just(stringArray).delayElements(Duration.ofMillis(delay));
    }
}

我是从文本文件获取字符数组,然后返回,当然你也可以从其他任何地方获取,仅仅是个示例而已

posted @ 2024-06-12 00:09  juyss  阅读(204)  评论(0编辑  收藏  举报