1、并发的瓶颈在于数据库(mysql),那如何减少对数据库的访问呢?
页面缓存:
package com.jack.seckill.redis;
public class GoodsKey extends BasePrefix{
private GoodsKey(int expireSeconds,String prefix) {
super(expireSeconds,prefix);
}
//页面缓存有效期都比较短,设置为60s,防止数据发生变化,页面还没有变
public static GoodsKey getGoodsList=new GoodsKey(60,"gl");
}
import com.jack.seckill.redis.RedisService;
import com.jack.seckill.service.GoodsService;
import com.jack.seckill.service.SeckillUserService;
import com.jack.seckill.vo.GoodsVo;
/**
* 跳转到商品页
*
*/
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
SeckillUserService userService;
@Autowired
RedisService redisService;
@Autowired
GoodsService goodsService;
@Autowired
ThymeleafViewResolver thymeleafViewResolver;
@Autowired
ApplicationContext applicationContext;
@RequestMapping("/to_list")
@ResponseBody
public String list(HttpServletRequest request,HttpServletResponse response,Model model,SeckillUser seckillUser) {
model.addAttribute("user123", seckillUser);
// return "goods_list";
//使用页面缓存技术
//第一步:从redis里面取缓存,看能否取到
String html=redisService.get(GoodsKey.getGoodsList, "", String.class);
if(!StringUtils.isEmpty(html)) {
return html;
}
//查询商品列表
List<GoodsVo> goodsList=goodsService.listGoodsVo();
model.addAttribute("goodsList", goodsList);
//第二步:没有从缓存取出,就手动进行渲染[ctrl+shift+T 打开open type ctrl+T打开看继承关系]
SpringWebContext ctx=new SpringWebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap(),applicationContext);
html=thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
if(!StringUtils.isEmpty(html)) {
//第三步:保存到缓存里面去
redisService.set(GoodsKey.getGoodsList, "", html);
}
return html;
}
}