springboot 返回流式数据

@PostMapping("/stream")
public ResponseEntity<StreamingResponseBody> stream() {
    StreamingResponseBody stream = out -> {
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            out.write(("This is line " + i + "\n").getBytes());
            out.flush();
        }
    };
    return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(stream);
}
posted @ 2023-06-08 10:42  FromZeroToOne  阅读(1832)  评论(0编辑  收藏  举报