废话就不多言了 直接上代码
@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即可
不惜勿喷,欢迎指正