网上搜了好多都是用 SseEmitter 实现的,自己搭的demo确实也可以了,但是我项目里有一个过滤器,死活配置都不行,终于用google搜了一下,第一篇帖子便解决了这个问题,代码和大佬链接如下:
https://github.com/CodingChaozhang/spring_boot_practice_demo/blob/master/springboot_sse/Spring%20boot%E6%95%B4%E5%90%88SSE%E5%AE%9E%E7%8E%B0%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%AE%9E%E6%97%B6%E6%8E%A8%E9%80%81%E6%B5%81%E4%BF%A1%E6%81%AF.md
@GetMapping(value = "/getTrue")public void getData_True(HttpServletResponse response) {response.setContentType("text/event-stream");response.setCharacterEncoding("utf-8");System.out.println("准备发消息");try {PrintWriter pw = response.getWriter();for (int i = 0; i < 5; i++) {if (pw.checkError()) {System.out.println("客户端断开连接");break;}Thread.sleep(1000);String ss = "data:实时返回的随机数:" + Math.random() + "\n\n";System.out.println(i + " " + ss);pw.write(ss);pw.flush();}pw.close();} catch (IOException | InterruptedException e) {e.printStackTrace();}System.out.println("发消息完毕");}