一 点睛
服务器推送技术在日常开发中较为常用。
SSE:Server send Event:服务端发送事件。
本项目推送技术是基于:当客户端向服务端发送请求,服务端会抓住这个请求不放,等有数据更新的时候才返回给客户端,当客户端接收到消息后,再向服务端发送请求,周而复始。这种方式的好处是减少了服务器的请求数量,大大减少了服务器的压力。
二 实战
1 控制器
package com.wisely.highlight_springmvc4.web.ch4_5;import java.util.Random;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class SseController {//这里使用输出的媒体类型为text/event-stream,这是服务端的SSE的支持@RequestMapping(value="/push",produces="text/event-stream") public @ResponseBody String push(){Random r = new Random();try {//演示每5秒向浏览器推送随机消息Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} return "data:Testing 1,2,3" + r.nextInt() +"\n\n";}}
2 演示页面
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SSE Demo</title>
</head>
<body>
<div id="msgFrompPush"></div>
<script type="text/javascript" src="<c:url value="assets/js/jquery.js" />"></script>
<script type="text/javascript">if (!!window.EventSource) { //EventSource对象只有新式的浏览器才有(Chrome、Firefox)等,EventSource是SSE的客户端var source = new EventSource('push');s='';//添加SSE客户端监听,在此获得服务器端推送的消息source.addEventListener('message', function(e) {s+=e.data+"<br/>";$("#msgFrompPush").html(s);});source.addEventListener('open', function(e) {console.log("连接打开.");}, false);source.addEventListener('error', function(e) {if (e.readyState == EventSource.CLOSED) {console.log("连接关闭");} else {console.log(e.readyState); }}, false);} else {console.log("你的浏览器不支持SSE");}
</script>
</body>
</html>
三 配置
添加转向sse.jsp页面的映射:
@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/sse").setViewName("/sse");}
四 实战
浏览http://localhost:8080/highlight_springmvc4/sse