springboot中SSE的使用(SERVER SENT EVENT)

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:50   1411   0

废话就不多言了 直接上代码

@GetMapping(value="/pushMonitorData",produces = "text/event-stream;charset=UTF-8" )
@ApiOperation(value = "推送cpu")
public String pushMonitorData(){
    JSONObject object = new JSONObject();
    object.put("cpuUsage", Constant.CPU_QUUE);
    object.put("memoryUsage",Constant.MOMORY_QUEUE);
    try {
        Thread.sleep(1000*30);
        return "data:" +getData() + "\n\n";
    }catch (Exception e) {
        log.info("推送cpu数据异常,错误信息是:"+e.getMessage());
    }
    //!!!注意,EventSource返回的参数必须以data:开头,"\n\n"结尾,不然onmessage方法无法执行。
    return "data:" +"{\"msg\":\"fail\",\"code\":1,\"body\":null}" + "\n\n";
}

个人感觉 跟其他restcontroller的区别应该就是produces的区别,前端这里

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//需要判断浏览器支不支持,可以去w3c进行查看

var source = new EventSource('http://localhost:8090/pushMonitorData');
source.onmessage = function (event) {
console.info(event.data);
document.getElementById('result').innerText = event.data
};

</script>
</head>

<body>
<div id="result"></div>
</body>


</html>

直接new 一个EventSource即可

不惜勿喷,欢迎指正

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP