✅P242_商城业务-购物车-添加购物车细节

gong_yz小于 1 分钟谷粒商城

添加购物车细节

上面的操作是针对添加新商品进购物车,若购物车里已存在此商品则是一个数量的叠加

cfmall-cart/src/main/java/com/gyz/cfmall/service/impl/CartServiceImpl.java

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ThreadPoolExecutor executor;
    @Resource
    private ProductFeignService productFeignService;

    private final String CART_PREFIX = "cfmall:cart:";

    @Override
    public CartItemVo addCartItem(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        String item = (String) cartOpts.get(skuId.toString());

        if (StringUtils.isEmpty(item)) {
            CartItemVo cartItemVo = new CartItemVo();

            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加商品的信息
                R productSkuInfo = productFeignService.skuInfo(skuId);
                SkuInfoVo skuInfo = productSkuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //数据赋值操作
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, executor);

            CompletableFuture<Void> getSkuSaleAttrFuture = CompletableFuture.runAsync(() -> {
                //2、获取销售属性
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoFuture, getSkuSaleAttrFuture).get();

            String carItemInfo = JSON.toJSONString(cartItemVo);
            cartOpts.put(skuId.toString(), carItemInfo);
            return cartItemVo;
        } else {
            //购物车有此商品,修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(item, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOpts.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        }
    }

    private BoundHashOperations<String, Object, Object> getCartOpts() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps(cartKey);
        return boundHashOps;
    }
}