springboot 使用thymeleaf 完成页面缓存

直接看Demo

注入redisservice以及其余两个bean.

  @Autowired
    private RedisService redisService;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private WebApplicationContext applicationContext;

控制层:

 @RequestMapping(value="/list",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String showGoods(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response){

        //1.从redis缓存中查询
        String listHtml = redisService.get("goosList",String.class);
        if(StringUtils.isNotEmpty(listHtml)){
            return  listHtml;
        }


        //2.使用thymeleaf模板引擎手动渲染视图
        List<MiaoshaGoods> goodsList = miaoshaGoodsService.selectAllMiaoshaGoods();
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsList);

       // 无法导入SpringWebContext的包
        SpringWebContext context = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);

        String html = thymeleafViewResolver.getTemplateEngine().process("goods_list",context);


        //3.将手动渲染后的html存入redis缓存
        if(StringUtils.isNotEmpty(html)){
            redisService.set("goosList",html);
        }

        return html;

    }

核心点是:

     SpringWebContext context = new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);

        String html = thymeleafViewResolver.getTemplateEngine().process("goods_list",context);

猜你喜欢

转载自blog.csdn.net/weixin_41868360/article/details/81488355
今日推荐