SpringBoot2.x服务端主动推送SSE

讲解SpringBoot2.x服务端主动推送Sever-Send-Events
        
    1、localhost:8080/index.html
    2、需要把response的类型 改为 text/event-stream,才是sse的类型

   调用的controller

   

@RestController
@RequestMapping("/sse")
public class SSEController {

    @RequestMapping(value = "/get_data", produces = "text/event-stream;charset=UTF-8")
    public String push() {
          
          try {
              Thread.sleep(1000); 
              //第三方数据源调用
          } catch (InterruptedException e) {
              e.printStackTrace();
          }

          return "data:xdclass 行情" + Math.random() + "\n\n";
    }
}

对应的index.html页面

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

var source = new EventSource('sse/get_data');
source.onmessage = function (event) {
  console.info(event.data);
  document.getElementById('result').innerText = event.data
};

</script>  
</head>

<body>
模拟股票行情
 <div>xdclass test</div>  
    <div id="result"></div>  
</body>


</html>

猜你喜欢

转载自blog.csdn.net/peng_0129/article/details/85783639