文章目录
页面缓存
为什么要加缓存
页面加载时间会显着影响用户体验,谷歌的实验表明,加载时间仅相差半秒,就可以将网络流量减少多达20%。而页面缓存技术可以改善网页的加载时间。
缓存的页面作为静态HTML,避免了对数据库的耗时查询。 实际上,页面缓存可以将服务器负载降低多达80%,这对于使用数据库信息以便将页面提供给用户的高流量网站特别有利。当然,页面缓存的缺点是用户无法查看页面的最新版本。但是,对于不包含动态功能或经常添加新信息的网站,这是用户快速查看该网站的最佳方式。
加缓存前
前端使用Thymleaf开发,服务收到to_list的请求之后,查询数据库得到数据,放入model中传给前端页面。
GoodsController.java
@Autowired
GoodsService goodsService;
@RequestMapping("/to_list")
public String toList(Model model
){
List<GoodsVo> list = goodsService.listGoodsVo(); //查询数据库
model.addAttribute("goodsList",list);
return "goods_list";
}
goods_list.html
<body>
<div>
<div>秒杀商品列表</div>
<table>
<tr><td>商品名称</td><td>商品图片</td><td>商品原价</td><td>秒杀价</td><td>库存数量</td><td>详情</td></tr>
<tr th:each="goods,goodsStat : ${goodsList}">
<td th:text="${goods.goodsName}"></td>
<td ><img th:src="@{${goods.goodsImg}}" width="100" height="100" /></td>
<td th:text="${goods.goodsPrice}"></td>
<td th:text="${goods.miaoshaPrice}"></td>
<td th:text="${goods.stockCount}"></td>
<td><a th:href="'/goods/to_detail/'+${goods.id}">详情</a></td>
</tr>
</table>
</div>
</body>
压测结果:
线程数1000,每个线程在同一时间发送3个请求。
可以看出,整体的吞吐量是20/s左右。
加缓存后
在服务受到to_list的请求的时候,先去redis中查询有没有缓存,如果有的话直接返回。没有的话就去数据库中查到数据,然后手动渲染页面,存入redis中(生存时间是60秒),返回结果。
@Autowired
MiaoshaUserService userService;
@Autowired
RedisService redisService;
@Autowired
GoodsService goodsService;
@Autowired
ThymeleafViewResolver thymeleafViewResolver;
@Autowired
ApplicationContext applicationContext;
@RequestMapping(value="/to_list", produces="text/html")
@ResponseBody
public String