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>