研究一种后端向前端推送数据的操作,叫SSE(Server-Sent Events),但是,我觉得这玩意就是轮询。算了,烦的要死,记录下这种方式把。
前端代码是vue写的,EventSource里面是后端的接口地址
mounted() { var es = new EventSource(this.common.httpUrl + '/home/home') es.addEventListener('message', function(e) { console.log(e.data) }) },
后端代码是java springboot写的,需要注意一定得加上"\n\n",不然无效.....我特么也不知道为什么有这神奇效果。
@GetMapping("home") public ResponseEntity<?> home() { HttpHeaders header = new HttpHeaders(); header.add("Content-Type", "text/event-stream"); String string = new Date().toString(); return ResponseEntity.ok().headers(header).body("data: " + string+ "\n\n"); }
然后前端就可以看到一只打印出后台的东西,3秒发一次请求。不是我要做到东西,就研究到这里。