Spring使用event-stream进行数据推送
作者:zyydd_
这篇文章主要介绍了Spring使用event-stream进行数据推送,前端使用EventSource方式向后台发送请求,后端接收到之后使用event-stream方式流式返回,文中有相关的代码示例供大家参考,需要的朋友可以参考下
前端使用EventSource方式向后台发送请求,后端接收到之后使用event-stream方式流式返回。可以应用在时钟、逐字聊天等场景。
前端js示例代码(向后台请求数据,并展示到“id=date”的div上)
<script type="text/javascript"> if (typeof (EventSource) !== "undefined") { var eventSource = new EventSource("${root}/test/getDate"); eventSource.onmessage = function (event) { document.getElementById("date").innerHTML = event.data; } eventSource.addEventListener('error', function (event) { console.log("错误:" + event); }); eventSource.addEventListener('open', function (event) { console.log("建立连接:" + event); }); } else { document.getElementById("date").innerHTML = "抱歉,您的浏览器不支持EventSource事件 ..."; } </script>
后端java示例
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.util.Date; @Controller @RequestMapping(value = "/test") public class TestController { @ResponseBody @RequestMapping(value = "/getDate", produces = "text/event-stream;charset=UTF-8") public void getDate(HttpServletResponse response) throws Exception { System.out.println("getDate event start"); response.setContentType("text/event-stream"); response.setCharacterEncoding("UTF-8"); response.setStatus(200); for (int i = 0; i < 10; i++) { response.getWriter().write("data:" + new Date() + "\n\n"); response.getWriter().flush(); Thread.sleep(1000); } response.getWriter().close(); System.out.println("getDate event end"); } }
除了是这个方法,我们也可以使用Spring的定时器定时推送数据
定时器编写
1.在配置文件里添加相关配置
<!-- 定时器开关 --> <task:annotation-driven /> <!-- 自动扫描的包名 --> <bean id="myTaskXml" class="定时方法所在的类的完整类名"></bean> <task:scheduled-tasks> <task:scheduled ref="myTaskXml" method="appInfoAdd" cron="*/5 * * * * ?"/> </task:scheduled-tasks>
上面的代码设置的是每5秒执行一次appInfoAdd方法,cron字段表示的是时间的设置,分为:秒,分,时,日,月,周,年。
2.定时方法的编写
Logger log = Logger.getLogger(TimerTask.class);; public void apiInfoAdd(){ InputStream in = TimerTask.class.getClassLoader().getResourceAsStream("/system.properties"); Properties prop = new Properties(); try { prop.load(in); } catch (IOException e) { e.printStackTrace(); } String key = prop.getProperty("DLKEY"); log.info("key--" + key); //锁数据操作 List<GbEsealInfo> list = this.esealService.loadBySendFlag("0"); if (list == null) { log.info("没有需要推送的锁数据"); }else{ JsonObject json = new JsonObject(); JsonArray ja = new JsonArray(); json.add("esealList", ja); for(int i = 0; i < list.size(); i++) { GbEntInfo ent = this.entService.loadByPk(list.get(i).getEntId()); JsonObject esealJson = getEsealJson(list.get(i), ent); ja.add(esealJson); } String data = json.toString(); log.info("锁数据--" + data); HttpDeal hd = new HttpDeal(); Map<String,String> map = new HashMap<String, String>(); map.put("key",key); map.put("data", data); hd.post(prop.getProperty("ESEALURL"), map); log.info(hd.responseMsg); JsonObject returnData = new JsonParser().parse(hd.responseMsg).getAsJsonObject(); if (("\"10000\"").equals(returnData.get("code").toString())){ log.info("锁数据推送成功"); for(int i = 0; i < list.size(); i++){ list.get(i).setSendFlag("1"); int res = this.esealService.updateSelectiveByPk(list.get(i)); if(res == 0){ log.info("第" + (i+1) + "条锁数据的sendflag字段的状态值修改失败"); continue; } } } }
这个过程包括读取配置文件里的key,从数据库读取数据(根据数据的字段判断是否需要推送),使用GSON把数据拼装成上一篇文章里的data的形式data={"esealList":[{},{},{}]},使用HttpClient执行带参数的POST方法,访问POST接口,根据返回信息判断状态。
3.HttpClient里的带参POST方法
public class HttpDeal { public String responseMsg; public String post(String url,Map<String, String> params){ //实例化httpClient CloseableHttpClient httpclient = HttpClients.createDefault(); //实例化post方法 HttpPost httpPost = new HttpPost(url); //处理参数 List<NameValuePair> nvps = new ArrayList <NameValuePair>(); Set<String> keySet = params.keySet(); for(String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } //结果 CloseableHttpResponse response = null; String content=""; try { //提交的参数 UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8"); //将参数给post方法 httpPost.setEntity(uefEntity); //执行post方法 response = httpclient.execute(httpPost); if(response.getStatusLine().getStatusCode()==200){ content = EntityUtils.toString(response.getEntity(),"utf-8"); responseMsg = content; //System.out.println(content); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return content; } public static void main(String[] args) { HttpDeal hd = new HttpDeal(); Map<String,String> map = new HashMap(); map.put("key","5c07db6e22c780e76824c88b2e65e9d9"); map.put("data", "{'esealList':[{'esealId':'1','entName':'q','entName':企业,'id':'qqww','id':'123', 'customsCode':'qq','fax':'021-39297127'}]}"); hd.post("http://localhost:8080/EportGnssWebDL/api/CopInfoAPI/esealInfoAdd.json",map); } }
4.辅助类
/** * 辅助类:锁接口需要的字段 * @param eseal * @param ent * @return */ private JsonObject getEsealJson(GbEsealInfo eseal, GbEntInfo ent){ JsonObject j = new JsonObject(); j.addProperty("esealId", eseal.getEsealId()); j.addProperty("vehicleNo", eseal.getVehicleNo()); j.addProperty("customsCode", eseal.getCustomsCode()); j.addProperty("simNo", eseal.getSimNo()); j.addProperty("entName", ent.getEntName()); j.addProperty("customsName", eseal.getCustomsName()); j.addProperty("leadingOfficial", ent.getLeadingOfficial()); j.addProperty("contact", ent.getContact()); j.addProperty("address", ent.getAddress()); j.addProperty("mail", ent.getMail()); j.addProperty("phone", ent.getPhone()); j.addProperty("fax", ent.getFax()); return j; }
以上就是Spring使用event-stream进行数据推送的详细内容,更多关于Spring event-stream数据推送的资料请关注脚本之家其它相关文章!