服务器给前端实时推送数据轻量化解决方案eventSource+Springboot

一、前端代码

body代码

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("错误:" + event);
        });
        source.addEventListener('open', function (event) {
            console.log("建立连接:" + event);
        });
    } else {
        document.getElementById("result").innerHTML="抱歉,你的浏览器不支持 server-sent 事件...";
    }
})

二、后端代码

WebFlux 框架依赖jar包


    org.springframework.boot
    spring-boot-starter-webflux

控制器代码

@GetMapping(value = "/getTime",produces="text/event-stream;charset=UTF-8")
@ApiOperationSupport(order = 1)
@ApiOperation(value = "详情", notes = "传入name")
public Flux getTime() {
	return Flux.interval(Duration.ZERO,Duration.ofSeconds(1)).map(i -> "最新时间:" + DateUtil.time() + "-" + i);
}

Flux.interval(Duration.ZERO,Duration.ofSeconds(1)),等待0秒开始,间隔1秒,Flux流数据里面的数字加1
三、效果展示
服务器给前端实时推送数据轻量化解决方案eventSource+Springboot_第1张图片时间和数字一直在增加,后端在不断推送,前端订阅到数据更新到页面

相对于websocket简单很多,只需要很少的代码就实现前端数据的实时刷新,只不过eventSource是单向数据通信,websocket可实现双向通信。

你可能感兴趣的:(JavaWeb,spring,boot,eventSource,实时消息推送)