基于Redis优化购物车 - 添加商品

    科技2025-10-27  7

    @ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车", httpMethod = "POST") @PostMapping("/add") public JSONResult add( @RequestParam String userId, @RequestBody ShopcartBO shopcartBO, HttpServletRequest request, HttpServletResponse response ) { if (StringUtils.isBlank(userId)) { return JSONResult.errorMsg(""); } System.out.println(shopcartBO); // 前端用户在登录的情况下,添加商品到购物车,会同时在后端同步购物车到redis缓存 // 需要判断当前购物车中包含已经存在的商品,如果存在则累加购买数量 String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId); List<ShopcartBO> shopcartList = null; if (StringUtils.isNotBlank(shopcartJson)) { // redis中已经有购物车了 shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBO.class); // 判断购物车中是否存在已有商品,如果有的话counts累加 boolean isHaving = false; for (ShopcartBO sc: shopcartList) { String tmpSpecId = sc.getSpecId(); if (tmpSpecId.equals(shopcartBO.getSpecId())) { sc.setBuyCounts(sc.getBuyCounts() + shopcartBO.getBuyCounts()); isHaving = true; } } if (!isHaving) { shopcartList.add(shopcartBO); } } else { // redis中没有购物车 shopcartList = new ArrayList<>(); // 直接添加到购物车中 shopcartList.add(shopcartBO); } // 覆盖现有redis中的购物车 redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartList)); return JSONResult.ok(); } public static final String FOODIE_SHOPCART = "shopcart"; @ApiOperation(value = "获取商品子分类", notes = "获取商品子分类", httpMethod = "GET") @GetMapping("/subCat/{rootCatId}") public JSONResult subCat( @ApiParam(name = "rootCatId", value = "一级分类id", required = true) @PathVariable Integer rootCatId) { if (rootCatId == null) { return JSONResult.errorMsg("分类不存在"); } List<CategoryVO> list = new ArrayList<>(); String catsStr = redisOperator.get("subCat:" + rootCatId); if (StringUtils.isBlank(catsStr)) { list = categoryService.getSubCatList(rootCatId); /** * 查询的key在redis中不存在, * 对应的id在数据库也不存在, * 此时被非法用户进行攻击,大量的请求会直接打在db上, * 造成宕机,从而影响整个系统, * 这种现象称之为缓存穿透。 * 解决方案:把空的数据也缓存起来,比如空字符串,空对象,空数组或list */ if (list != null && list.size() > 0) { redisOperator.set("subCat:" + rootCatId, JsonUtils.objectToJson(list)); } else { redisOperator.set("subCat:" + rootCatId, JsonUtils.objectToJson(list), 5*60); } } else { list = JsonUtils.jsonToList(catsStr, CategoryVO.class); } // List<CategoryVO> list = categoryService.getSubCatList(rootCatId); return JSONResult.ok(list); }

     

    Processed: 0.016, SQL: 8