本文主要是介绍8 缓存实现,减少数据库访问,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1 页面缓存
1 添加自定义Key类
public class GoodsKey extends BasePrefix {
private GoodsKey(int expireSecondes, String prefix) {
super(expireSecondes, prefix); }
public static GoodsKey getGoodsList = new GoodsKey(60000, "goodslist"); public static GoodsKey getGoodsDetail = new GoodsKey(60000, "goodsdetail");}
2 修改Controller
// @RequestMapping("/to_list") @RequestMapping(value="/to_list", produces="text/html")
@ResponseBody public String toLogin(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response){
model.addAttribute("user", user); // 查询商品列表 List<GoodsVo> goodsList = goodsService.listGoodsVo(); model.addAttribute("goodsList", goodsList);// return "goods_list"; // 取缓存 String html = redisService.get(GoodsKey.getGoodsList, "", String.class); if(!StringUtils.isEmpty(html)){
return html; }
// 手动渲染 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; }
2 对象缓存
# 测试
java -jar miaosha.jar
# 如果遇到tomcat端口已经被占用 了,那就去将占用改端口的pid给kill掉
# 具体方法:
ps -ef | grep miaosha.jar
# 然后重新部署项目,然后测试
java -jar miaosha.jar 2>&1
rm -f *.jtl
./apache-jmeter-5.4.1/bin/jmeter.sh -n -t miaosha_to_list_add_redis_5000_10.jmx -l miaosha_to_list_add_redis_5000_10.jtl
这篇关于8 缓存实现,减少数据库访问的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!