springboot 使用thymeleaf 完成页面缓存

本文介绍了一种结合Thymeleaf模板引擎和Redis缓存技术实现商品列表页面动态渲染及缓存的方法。通过在控制器中注入相关服务,并利用SpringWebContext上下文,实现了对页面数据的手动渲染并将其缓存到Redis中,从而有效提高页面加载速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接看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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值