购物车的添加方法无法将数据添加到redis数据库中,老师我自己找了一下问题,没有找出来,麻烦老师看一下
来源:11-4 购物车-添加商品-2

潜龙勿用s
2020-01-11
写回答
3回答
-
报错信息发一下。
052020-01-14 -
潜龙勿用s
提问者
2020-01-12
// CartServiceImpl.java 文件中add()方法的的代码 package com.imooc.mall.service.impl; import com.google.gson.Gson; import com.imooc.mall.dao.ProductMapper; import com.imooc.mall.enums.ProductStatusEnum; import com.imooc.mall.enums.ResponseEnum; import com.imooc.mall.form.CartAddForm; import com.imooc.mall.pojo.Cart; import com.imooc.mall.pojo.Product; import com.imooc.mall.service.ICartService; import com.imooc.mall.service.vo.CartProductVo; import com.imooc.mall.service.vo.CartVo; import com.imooc.mall.service.vo.ResponseVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class CartServiceImpl implements ICartService { @Autowired private ProductMapper productMapper; @Autowired private StringRedisTemplate redisTemplate; // 将对象转化成json字符串 private Gson gson = new Gson(); // 购物车id private final static String CART_REDIS_KEY_TEMPLATE = "cart_%d"; // 向购物车中添加商品 @Override public ResponseVo<CartVo> add(Integer uid, CartAddForm form) { Integer quantity = 1; Product product = productMapper.selectByPrimaryKey(form.getProductId()); // 1. 判断商品是否存在 if (product == null) { return ResponseVo.error(ResponseEnum.PRODUCT_NOT_EXIST); } // 2. 判断商品是否在售 if (product.getStatus().equals(ProductStatusEnum.ON_SALE.getCode())) { return ResponseVo.error(ResponseEnum.PRODUCT_OFF_SALE_OR_DELETE); } // 3. 判断商品的库存是否充足 if (product.getStock() <= 0) { return ResponseVo.error(ResponseEnum.PRODUCT_STOCK_ERROR); } // 4. 校验完毕后,写入数据到 redis中 HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash(); String redisKey = String.format(CART_REDIS_KEY_TEMPLATE, uid); String value = opsForHash.get(redisKey, String.valueOf(product.getId())); Cart cart; if (StringUtils.isEmpty(value)) { // 如果 value 为空,说明购物车中没有该商品,新增 cart = new Cart(product.getId(), quantity, form.getSelected()); } else { // 如果存在, 则商品的数量 +1 cart = gson.fromJson(value, Cart.class); cart.setQuantity(cart.getQuantity() + quantity); } opsForHash.put(redisKey, String.valueOf(product.getId()), gson.toJson(cart)); return list(uid); }
022020-01-26 -
xialei
2020-01-11
只有测试语句,怎么看?
00
相似问题