1. 程式人生 > >springboot2.x簡單詳細教程--伺服器端主動推送SSE技術講解(第十六章)

springboot2.x簡單詳細教程--伺服器端主動推送SSE技術講解(第十六章)

一、服務端推送常用技術介紹


    簡介:服務端常用推送技術介紹,如websocket,sse輪詢等
        1、客戶端輪詢:ajax定時拉取(延遲1s)

        2、服務端主動推送:WebSocket (時時重新整理延遲1毫秒
            全雙工的,本質上是一個額外的tcp連線,建立和關閉時握手使用http協議,其他資料傳輸不使用http協議
            更加複雜一些,適用於需要進行復雜雙向資料通訊的場景

        3、服務端主動推送:SSE (Server Send Event)時時重新整理延遲1毫秒
            html5新標準,用來從服務端實時推送資料到瀏覽器端
            直接建立在當前http連線上,本質上是保持一個http長連線,輕量協議
            簡單的伺服器資料推送的場景,使用伺服器推送事件    
            學習資料:http://www.w3school.com.cn/html5/html_5_serversentevents.asp

二、SpringBoot2.x服務端主動推送SSE


    簡介:講解SpringBoot2.x服務端主動推送Sever-Send-Events
        
    1、localhost:8080/index.html
    2、需要把response的型別 改為 text/event-stream,才是sse的型別

 1)controller(服務端)

package com.itcast.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@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";
    }
}

2)resources/public/下建立html檔案 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//需要判斷瀏覽器支不支援EventSource,可以去w3c進行檢視
	/* 
	 EventSource:服務端推送的物件 (source) ,建構函式傳入地址
	 onmessage:監聽器
	 event:訊息
	 */
	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>lanpo test</div>
	<div id="result"></div>
</body>


</html>

3)

總結:服務端主動s推送:SSE是 單方的資料更新

WebSocket 是雙向的資料更新,方便專案後期擴充套件:推薦使用這個