Springboot 通过SSE 实现实时消息返回

网上搜了好多都是用 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("发消息完毕");
    }

在这里插入图片描述

相关推荐

  1. gin+sse实现离散的消息通知

    2024-06-08 11:42:01       14 阅读
  2. springboot redis 实现消息队列

    2024-06-08 11:42:01       29 阅读
  3. 实时通信websocket和sse

    2024-06-08 11:42:01       6 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 11:42:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 11:42:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 11:42:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 11:42:01       18 阅读

热门阅读

  1. CAB203 Special Topics Assignment

    2024-06-08 11:42:01       8 阅读
  2. 智能合约中未授权访问

    2024-06-08 11:42:01       7 阅读
  3. Visual Studio的快捷按键

    2024-06-08 11:42:01       9 阅读
  4. Docker面试整理-如何管理Docker容器的安全?

    2024-06-08 11:42:01       12 阅读
  5. 52.Fork & Join线程池

    2024-06-08 11:42:01       7 阅读
  6. Fiddler无法显示捕获到的网络流量的问题处理方法

    2024-06-08 11:42:01       12 阅读