幸运飞艇平台开发 http://haozbbs.com/ Q1446595067
首先跟着楼主来简单了解一下页面缓存的含义:
页面缓存
页面缓存是将动态页面直接生成静态的页面放在服务器端, 用户调取相同页面时, 静态页面将直接下载到客户端, 不再需要通过程序的运行和数据库的访问, 大大节约了服务器的负载. 每次访问页面时, 会检测相应的缓存页面是否存在, 若不存在, 则连接数据库得到数据渲染页面并生成缓存页面文件, 这样下次访问的页面文件就发挥作用了.
接下来楼主将用一个简单的例子来带大家走进页面缓存的世界:
1. 假如有一个这样的代码 (他的功能是展现商品的列表, 这里讲的框架是 SpringBoot, 前端用的 themleaf 模板)
- @RequestMapping("/goods/to_list")
- public String list(Model model, MiaoshaUser user ) {
- model.addAttribute("user", user);
- // 查询商品列表
- List<GoodsVo> goodsList = goodsService.listGoodsVo();
- model.addAttribute("goodsList", goodsList);
- return "goods_list";
- }
我们从上面的代码得知: 该代码是查询出商品列表然后转到 goods_list.html 的前端页面上 (配置文件省略), 我们可以得知. 将 goodsList 参数通过 model 传给 goods_list 页面, 这其中是通过 SpringBoot 框架来进行渲染的. 其中牵扯很多代码的运行, 比较耗时间; 而且每执行这个代码一次, SpringBoot 就要渲染一次, 非常的麻烦;
2. 接下来我们就按照上面的例子作为例子来讲解页面的缓存 (使用页面缓存的代码如下:)
- @RequestMapping(value = "/goods/to_list", produces = "text/html")
- @ResponseBody
- public String list(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response) {
- model.addAttribute("user", user);
- // 查询商品列表
- List<GoodsVo> goodsList = goodsService.listGoodsVo();
- model.addAttribute("goodsList", goodsList);
- // 使用页面缓存 1. 查询 redis 对应的缓存 2. 不存在则写入 redis 缓存中
- // 1. 查询 redis
- String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
- if (!StringUtils.isEmpty(html)) {
- return html;
- }
- // 假如 redis 查询不到数据, 则: 熏染 html(通过 SpringBoot 的 themleafViewResovler 接口的实现类 SpringwebContext 来操作)
- SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(), request.getLocale(),
- model.asMap(), applicationContext);
- // 手动进行渲染: thymeleafViewResolver
- html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
- // 2. 将手动渲染完毕的 html 存放到 redis 中
- if (!StringUtils.isEmpty(html)) {
- redisService.set(GoodsKey.getGoodsList, "", html);
- }
- return html;
- }
我们从上面的代码得知: 页面缓存是首先从 redis 中取出渲染好的页面, 如果不存在, 那么则自己手动渲染页面一次, 再把通过
thymeleafViewResolver 渲染好的页面存入到缓存中去! 我们设置的页面缓存时间为 60s(在配置文件中, 这里就省略了), 说明多个请求对于这段代码来说, 在 60s 内都只会从缓存中去取, 这样大大的提高了效率, 节省了很多时间
使用场景: 页面缓存多用于变化不明显的页面, 比如商品列表等等!
来源: http://www.bubuko.com/infodetail-2692552.html