一、前端代碼
body代碼
<div id="result"></div>
js代碼
$(function(){
if(typeof(EventSource) != "undefined")
{
var source = new EventSource("/demo/getTime");
source.onmessage = function(event) {
console.log(event.data);
$("#result").html(event.data);
};
source.addEventListener('error', function (event) {
console.log("錯(cuò)誤:" + event);
});
source.addEventListener('open', function (event) {
console.log("建立連接:" + event);
});
} else {
document.getElementById("result").innerHTML="抱歉,你的瀏覽器不支持 server-sent 事件...";
}
})
二、后端代碼
WebFlux 框架依賴jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
控制器代碼
@GetMapping(value = "/getTime",produces="text/event-stream;charset=UTF-8")
@ApiOperationSupport(order = 1)
@ApiOperation(value = "詳情", notes = "傳入name")
public Flux<String> getTime() {
return Flux.interval(Duration.ZERO,Duration.ofSeconds(1)).map(i -> "最新時(shí)間:" + DateUtil.time() + "-" + i);
}
Flux.interval(Duration.ZERO,Duration.ofSeconds(1)),等待0秒開始,間隔1秒,F(xiàn)lux流數(shù)據(jù)里面的數(shù)字加1
三、效果展示時(shí)間和數(shù)字一直在增加,后端在不斷推送,前端訂閱到數(shù)據(jù)更新到頁(yè)面文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-847914.html
相對(duì)于websocket簡(jiǎn)單很多,只需要很少的代碼就實(shí)現(xiàn)前端數(shù)據(jù)的實(shí)時(shí)刷新,只不過(guò)eventSource是單向數(shù)據(jù)通信,websocket可實(shí)現(xiàn)雙向通信。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-847914.html
到了這里,關(guān)于服務(wù)器給前端實(shí)時(shí)推送數(shù)據(jù)輕量化解決方案eventSource+Springboot的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!