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

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));
    }
}

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

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值