SpringBoot模擬實現(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);
// 指示這是一個流式響應(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: '講個笑話'
})
});
const msg = await resp.text();
console.log(msg)
const endTime = performance.now();
console.log(`執(zhí)行耗時: ${endTime - startTime} ms`);
}
getResp()
測試結(jié)果如下,程序會等待所有內(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: '講個笑話'
})
});
const reader = resp.body.getReader();
while(1){
// value 是類型化數(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)容前端就會打印一段內(nèi)容。

以上就是SpringBoot模擬實現(xiàn)流式輸出效果的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot流式輸出的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Security登錄添加驗證碼的實現(xiàn)過程
這篇文章主要介紹了Spring Security登錄添加驗證碼的實現(xiàn)過程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11
SpringBoot整合達夢數(shù)據(jù)庫的教程詳解
這篇文章主要給大家介紹了SpringBoot整合達夢數(shù)據(jù)庫的詳細(xì)教程,文章中有詳細(xì)的圖片介紹和代碼示例供大家參考,具有一定的參考價值,需要的朋友可以參考下2023-08-08
SpringBoot調(diào)整ApplicationContextAware如何實現(xiàn)類加載順序
SpringBoot調(diào)整ApplicationContextAware實現(xiàn)類加載順序問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Java畢業(yè)設(shè)計實戰(zhàn)項目之倉庫管理系統(tǒng)的實現(xiàn)流程
這是一個使用了java+SSM+Maven+Bootstrap+mysql開發(fā)的倉庫管理系統(tǒng),是一個畢業(yè)設(shè)計的實戰(zhàn)練習(xí),具有一個倉庫管理系統(tǒng)該有的所有功能,感興趣的朋友快來看看吧2022-01-01

