【Java】SpringBoot模拟流式输出,前端使用流式接收数据并打印
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);
}
}