在高并发请求中(如秒杀系统)需要将请求尽量拦截在上游,减轻下游的压力,常用的在前端的方式有,限定点击次数,检测ip防止脚本式的攻击,页面静态化,后端一般使用消息队列+缓存的形式,一次来最大的拦截无用请求,最小化查询数据库次数,从而减轻服务器压力,达到高并发。今天就实战一下也页面静态化,学习之前请确保会springMVC的基本知识。
什么是页面静态化:我的理解就是对页面进行缓存,当请求来临时,我们直接用已有的缓存页面(包括需要从后端传来的数据,这样就不需要去后端查询了),所以在也页面静态化不适合实时查询,显示的数据可能与实际情况不一致,但这并影响系统的可用性(如秒杀系统中,显示的可能有剩余,当用户点击时,真正的数据发送过去后,库存没有会显示秒杀失败,这并不影响该系统的使用,缓存页面可每隔一段时间更新),一种常用的页面静态化手段是采用httpclient,发送请求给服务端,将响应的html页面写到文件当中,当请求来临时,直接请求缓存文件而不是直接去请求后端服务重新取用数据。请确保你配好springMVC相关逻辑,引入如下依赖
<!--页面静态化所需要依赖--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
页面静态化逻辑处理如下
@RequestMapping("producehtml") public void producehtml(HttpServletRequest httpServletRequest) { //放置静态页面的文件夹 String htmlPath = httpServletRequest.getRealPath("/WEB-INF/html/"); System.out.println(htmlPath); //请求路径,组成类似http + :// + 127.0.0.1 + : + 8080 + Msproject String contextpath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + httpServletRequest.getContextPath(); //请求静态化页面的逻辑,根据实际情况修改 contextpath = contextpath + "/pagehomeAction/home"; //创建一个请求客户端 CloseableHttpClient client = HttpClients.createDefault(); //模拟创建一个get请求,contextpath为请求路径 HttpGet httpGet = new HttpGet(contextpath); CloseableHttpResponse response = null; try { //模拟客户端发起请求,得到响应 response = client.execute(httpGet); //查看响应行 中的状态码 int responseCode = response.getStatusLine().getStatusCode(); System.out.println(responseCode); //响应实体,即传送的html,css等 页面内容, HttpEntity entity = response.getEntity(); if (entity != null) { //得到html页面,转为字符串形式 String html = EntityUtils.toString(entity); //将应用的static 页面 ,写到该文件中 File file = new File(htmlPath + "/index.html"); //将页面 写到对应的目录 Writer writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file), "utf-8")); writer.write(html); writer.flush(); writer.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
当然如果你的页面需要显示用户等信息,可以在页面使用ajax 异步发送请求,拿到信息,jquery代码如下
<script src="/Msproject/js/jquery-3.3.1.min.js"></script> <!--ajax异步发送请求 --> <script type="text/javascript"> $.ajax( { type: "get", url: "/Msproject/pagehomeAction/users/user", success: function (msg) { $("#useraccount").html(msg); } }); </script>
在springMVC的配置文件中引入如下配置
<!--静态页面配置-->
<mvc:resources mapping="/html/**" location="/WEB-INF/html/"/> <!--js也需要配置,因为js也是通过请求带过去的,springMVC照样会拦截,所以对于js资源路径 也需要额外配置--> <mvc:resources mapping="/js/**" location="/WEB-INF/classes/js"/>