解决方案一:websocketjavascript
解决方案二:ssehtml
原理:浏览器向服务器发送请求后,服务器抓住请求不放,等到数据更新时,服务器再把数据发送给浏览器,浏览器拿到响应后,再向服务器发送请求,如此循环java
好处:只使用了一次请求,大大减少了服务器的请求数量,减轻服务器压力,只会在接收到数据更新后才返回响应。web
栗子:ajax
服务端 springboot接收请求spring
@RestController
@Slf4j
public class PushController {
private int count;
/** * 超时时间设置到最大,避免由于超时致使链接断开 */
private SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
@GetMapping(value = "/push")
public SseEmitter push() throws InterruptedException {
return emitter;
}
@GetMapping("/send")
public String send() {
try {
emitter.send("push " + count++);
return "success";
} catch (IOException e) {
e.printStackTrace();
}
return "failed";
}
}
复制代码
客户端 js监听消息浏览器
<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>服务器推送示例</title>
</head>
<body>
<div id="msg"></div>
</body>
<script> var source = new EventSource("/springboot/push"); source.onmessage = function (e) { console.info("收到信息"); document.getElementById("msg").innerHTML += `<p>${e.data}</p>`; }; source.onopen = function (e) { console.info("链接打开"); console.info(e); }; source.onerror = function (e) { console.info("链接错误"); console.info(e); }; </script>
</html>
复制代码
每次访问send,服务器就会向浏览器返回数据springboot
能够看到一个push请求接收了来自服务器的多个数据服务器