页面缓存例子

转发页面:

一般都是controller将数据转发到指定的模板上,模板引擎(视图解析器)(modelAndView)帮我们去渲染页面,然后将渲染好的页面发给浏览器
另一种做法是,我们去用模板引擎加载数据,提前产生好页面,将这个页面的html语句作为json发送给浏览器

 @RequestMapping(value="/to_list",produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user) {
        // 一般是token,然后对token从redis取user,user为空抛异常跳转(或者给出异常json),这里通过argumentResolver来封装成user;

        //取缓存
        String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
        if(!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        /* return "goods_list";    普通转发页面*/
       SpringWebContext ctx = new SpringWebContext(request,response,
                request.getServletContext(),request.getLocale(), model.asMap(), applicationContext );
        //手动渲染
         html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);//两个参数,一个模板名称,一个是IContext的实现类

        //存入的不是list数据,而是整个静态页面级的缓存
        if(!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.getGoodsList, "", html);
        }
        return html;
    }
原文地址:https://www.cnblogs.com/brxHqs/p/9718498.html