SpringBoot模擬實(shí)現(xiàn)流式輸出效果
現(xiàn)在AI的接口由于生成內(nèi)容比較慢都是采用的流式輸出的方式。這里將模擬一下流式輸出。
后端接口
import cn.hutool.json.JSONUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping("/stream")
public ResponseEntity<StreamingResponseBody> streamData() {
Map<String, String> map = new HashMap<>();
map.put("content", "內(nèi)容");
StreamingResponseBody responseBody = outputStream -> {
try (PrintWriter writer = new PrintWriter(outputStream)) {
for (int i = 0; i < 10; i++) {
map.put("content", "內(nèi)容:" + i);
writer.println(JSONUtil.toJsonStr(map));
writer.flush();
// 模擬一些延遲
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
// 指示這是一個(gè)流式響應(yīng)
headers.setContentLength(-1L);
return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
}
}
傳統(tǒng)非流式-前端
url = 'http://127.0.0.1:8080/test/stream'
async function getResp(){
const startTime = performance.now();
console.log("非流式輸出")
const resp = await fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
content: '講個(gè)笑話(huà)'
})
});
const msg = await resp.text();
console.log(msg)
const endTime = performance.now();
console.log(`執(zhí)行耗時(shí): ${endTime - startTime} ms`);
}
getResp()
測(cè)試結(jié)果如下,程序會(huì)等待所有內(nèi)容都返回了,才輸出內(nèi)容

流式-前端
async function getRespStream(){
console.log("流式輸出")
const resp = await fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
content: '講個(gè)笑話(huà)'
})
});
const reader = resp.body.getReader();
while(1){
// value 是類(lèi)型化數(shù)組
const textDecoder = new TextDecoder()
const {done,value} = await reader.read();
if(done){
break
}
const str = textDecoder.decode(value)
console.log(str)
}
}
getRespStream()
可以看到后端只要輸出一段內(nèi)容前端就會(huì)打印一段內(nèi)容。

以上就是SpringBoot模擬實(shí)現(xiàn)流式輸出效果的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot流式輸出的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java 入門(mén)圖形用戶(hù)界面設(shè)計(jì)之單選按鈕
圖形界面(簡(jiǎn)稱(chēng)GUI)是指采用圖形方式顯示的計(jì)算機(jī)操作用戶(hù)界面。與早期計(jì)算機(jī)使用的命令行界面相比,圖形界面對(duì)于用戶(hù)來(lái)說(shuō)在視覺(jué)上更易于接受,本篇精講Java語(yǔ)言中關(guān)于圖形用戶(hù)界面的單選按鈕2022-02-02
關(guān)于在IDEA熱部署插件JRebel使用問(wèn)題詳解
這篇文章主要介紹了關(guān)于在IDEA熱部署插件JRebel使用問(wèn)題詳解,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
SpringBoot整合Redis實(shí)現(xiàn)高并發(fā)數(shù)據(jù)緩存的示例講解
這篇文章主要介紹了SpringBoot整合Redis實(shí)現(xiàn)高并發(fā)數(shù)據(jù)緩存,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
java如何給對(duì)象按照字符串屬性進(jìn)行排序
這篇文章主要介紹了java如何給對(duì)象按照字符串屬性進(jìn)行排序,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
簡(jiǎn)單了解SpringCloud運(yùn)行原理
這篇文章主要介紹了簡(jiǎn)單了解SpringCloud運(yùn)行原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
詳解Spring Security的formLogin登錄認(rèn)證模式
對(duì)于一個(gè)完整的應(yīng)用系統(tǒng),與登錄驗(yàn)證相關(guān)的頁(yè)面都是高度定制化的,非常美觀(guān)而且提供多種登錄方式。這就需要Spring Security支持我們自己定制登錄頁(yè)面,也就是本文給大家介紹的formLogin模式登錄認(rèn)證模式,感興趣的朋友跟隨小編一起看看吧2019-11-11
Caused?by:?java.lang.NumberFormatException:?For?input?s
這篇文章主要介紹了Caused?by:?java.lang.NumberFormatException:?For?input?string:?“port“,本文給大家分享完美解決方法,需要的朋友可以參考下2023-01-01
SpringBoot中多環(huán)境yml的配置與打包問(wèn)題
這篇文章主要介紹了SpringBoot中多環(huán)境yml的配置與打包問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Java編程中的防轉(zhuǎn)義和轉(zhuǎn)義技巧匯總
在編程過(guò)程中,我們常常需要處理特殊字符和特定上下文,以確保生成的內(nèi)容在正確的環(huán)境中能夠被解析和顯示,本文將介紹一些常見(jiàn)的防轉(zhuǎn)義或者轉(zhuǎn)義處理的編程技巧,需要的可以參考一下2023-07-07

