一、页面缓存优化

1.注入ThymeleafViewResolver和ApplicationContext

  1. @Autowired
  2. ThymeleafViewResolver thymeleafViewResolver;
  3. @Autowired
  4. ApplicationContext applicationContext;

2.取缓存

  1. //取缓存
  2. String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
  3. if (!StringUtils.isEmpty(html)){
  4. return html;
  5. }

3.无缓存时,手动渲染模板输出结果

  1. SpringWebContext ctx = new SpringWebContext(request,response,
  2. request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
  3. //手动渲染
  4. html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
  5. if (!StringUtils.isEmpty(html)){
  6. redisService.set(GoodsKey.getGoodsList,"",html);
  7. }
  8. return html;

二、页面静态化

1.通过ajax异步请求,js渲染页面

  1. $.ajax({
  2. url:"/goods/detail/"+goodsId,
  3. type:"GET",
  4. success:function(data){
  5. if(data.code == 0){
  6. render(data.data);
  7. }else{
  8. layer.msg(data.msg);
  9. }
  10. },
  11. error:function(){
  12. layer.msg("客户端请求有误");
  13. }
  14. });

2.修改 controller 层返回 Vo 对象

  1. GoodsDetailVo vo = new GoodsDetailVo();
  2. vo.setGoods(goods);
  3. vo.setUser(user);
  4. vo.setRemainSeconds(remainSeconds);
  5. vo.setMiaoshaStatus(miaoshaStatus);
  6. return Result.success(vo);