写个Servlet 阻塞式 IO流式推送的小例子方便以后复制粘贴用你可能会问那非阻塞是什么非阻塞是Spring web flux模块的东西本文记录只是记录servlet下面的流式实现新项目建议使用fluxSseEmitter由于是阻塞式IO所以如果不额外配置线程池spring会提示Performing asynchronous handling through the default Spring MVC SimpleAsyncTaskExecutor. This executor is not suitable for production use under load. Please, configure an AsyncTaskExecutor through the WebMvc config.意思就是没有配置任何线程池将使用默认线程池该线程池不建议在生产环境下使用所以新项目我这里强烈建议使用SSE的另一个实现也就是Spring-webfluxpackage 你的包名;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.springframework.http.MediaType;importorg.springframework.web.bind.annotation.*;importorg.springframework.web.servlet.mvc.method.annotation.SseEmitter;importjava.util.HashMap;importjava.util.Map;RestController RequestMapping(/v1/chat)publicclassShiWenTianTestController{publicSseEmittercreateEmitter(){returnnewSseEmitter(720_000L);}PostMapping(path/completions,producesMediaType.TEXT_EVENT_STREAM_VALUE)publicSseEmittercompletions(RequestBody String param)throws Exception{SseEmitter emittercreateEmitter();MapString,StringstreamDatanewHashMap();streamData.put(key1,value1);try{ObjectMapper objectMappernewObjectMapper();String jsonStringobjectMapper.writeValueAsString(streamData);for(inti0;i3;i){Thread.sleep(1000);// 实际开发中这个send方法应该放到异步方法中然后在另外一个线程一直// send这就比较麻烦所以建议使用spring-webflux框架而不是SseEmitteremitter.send(SseEmitter.event().name(EVENT_1).data(jsonString));}emitter.complete();}catch(Exception error){//log.error(流式生成事项发送给前端时产生了错误, error);emitter.completeWithError(error);}returnemitter;}}使用Postman发送流式请求我这里是端口号是12888每个项目可能不一样最终返回结果如下