springboot服务端怎么推送SSE

发布时间:2021-10-20 17:40:10 作者:柒染
来源:亿速云 阅读:343

springboot服务端怎么推送SSE,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

package com.demo.action;

import com.demo.serviceI.DemoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
public class DemoAction {

    @Autowired
    private DemoService demoService;

    /**
     * 健康检查json串模拟
     * @return
     */
    @RequestMapping(value = "health.json")
    public String healt(){

        return "{\"status\":\"UP\",\"diskSpace\":{\"status\":\"UP\",\"total\":249769230336,\"free\":71914618880,\"threshold\":10485760},\"db\":{\"status\":\"UP\",\"database\":\"MySQL\",\"hello\":1}}";
    }

    /**
     * 条件注解使用
     * @return
     */
    @RequestMapping(value = "user/info")
    public String info(){

        return demoService.info();
    }

    /**
     * 异步调用方法
     */
    @RequestMapping(value = "print")
    public void print(){
        for (int i = 0; i < 100; i++) {
            demoService.print(i);
        }
    }

    /**
     * 服务端推送技术
     */
    @RequestMapping(value = "serverPush",produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public String serverPush(){

        Map<String,String> demo = new HashMap<>(1);
        demo.put("name","张三"+new Random().nextInt());
        ObjectMapper objectMapper = new ObjectMapper();
        String s = "data:";
        try {
            s += objectMapper.writeValueAsString(demo)+"\n\n";
            System.out.println(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }


}

页面代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="application/javascript">
        if (!!window.EventSource) {
            var event = new EventSource("/serverPush");

            event.addEventListener('message', function(t) {
                var data = t.data;
                document.write(data+"<br/>")
            });

            event.addEventListener("open",function (t) {
                console.log("开启");
            },false);

            event.addEventListener("error",function (t) {
                if (t.readyState  == EventSource.CLOSED) {
                    console.log("关闭");
                }
            },false);



        }else{
            console.error("浏览器不支持");
        }


    </script>
</head>
<body>

</body>
</html>

注意使用过程中容易遇到的问题:

1.由于返回类型使用了text/event-stream,所以在服务端响应数据必须使用String或其他文本类型

2. 在返回数据时,必须用data:和\n\n分别开头和结尾;如:String.format("data:%s\n\n",data),这里将我坑惨,网上和书上资料只是给了个例子没有具体说明,找了半天没找到原因和前端链接成功就是触发不了message事件

springboot服务端怎么推送SSE

关于springboot服务端怎么推送SSE问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. 小程序订阅消息推送(含源码)java实现小程序推送,springboot实现微信消息推送
  2. C# 服务端推送,十步十分钟,从注册到推送成功。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:Tomcat中的连接器是如何设计的

下一篇:怎么进行SSM环境整合

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》