SpringBoot模擬實現(xiàn)流式輸出效果
更新時間:2025年03月17日 09:33:53 作者:果殼~
這篇文章主要為大家詳細介紹了如何使用SpringBoot模擬實現(xiàn)流式輸出效果,并在前端使用流式接收數(shù)據(jù)并打印,感興趣的小伙伴可以參考一下
現(xiàn)在AI的接口由于生成內容比較慢都是采用的流式輸出的方式。這里將模擬一下流式輸出。
后端接口
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", "內容"); StreamingResponseBody responseBody = outputStream -> { try (PrintWriter writer = new PrintWriter(outputStream)) { for (int i = 0; i < 10; i++) { map.put("content", "內容:" + 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); // 指示這是一個流式響應 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()
測試結果如下,程序會等待所有內容都返回了,才輸出內容
流式-前端
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()
可以看到后端只要輸出一段內容前端就會打印一段內容。
以上就是SpringBoot模擬實現(xiàn)流式輸出效果的詳細內容,更多關于SpringBoot流式輸出的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot整合Redis實現(xiàn)高并發(fā)數(shù)據(jù)緩存的示例講解
這篇文章主要介紹了SpringBoot整合Redis實現(xiàn)高并發(fā)數(shù)據(jù)緩存,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03詳解Spring Security的formLogin登錄認證模式
對于一個完整的應用系統(tǒng),與登錄驗證相關的頁面都是高度定制化的,非常美觀而且提供多種登錄方式。這就需要Spring Security支持我們自己定制登錄頁面,也就是本文給大家介紹的formLogin模式登錄認證模式,感興趣的朋友跟隨小編一起看看吧2019-11-11Caused?by:?java.lang.NumberFormatException:?For?input?s
這篇文章主要介紹了Caused?by:?java.lang.NumberFormatException:?For?input?string:?“port“,本文給大家分享完美解決方法,需要的朋友可以參考下2023-01-01SpringBoot中多環(huán)境yml的配置與打包問題
這篇文章主要介紹了SpringBoot中多環(huán)境yml的配置與打包問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09