Redis缓存实例:缓存购物车数据

 

思路:

Redis缓存实例:缓存购物车数据

 

 代码:

  @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addCart(String skuId, Integer num, String username) {

        /**
         * 1)查询redis中的数据
         * 2)如果redis中已经有了,则追加数量,重新计算金额
         * 3)如果没有,将商品添加到缓存
         */
        //redisTemplate.boundHashOps新增元素到指定键中
        OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps(CART + username).get(skuId);
        if (orderItem != null) {
            //存在,刷新购物车
            orderItem.setNum(orderItem.getNum() + num);
            //如果数量<=0,应该移除该商品
            if (orderItem.getNum()<= 0){
                redisTemplate.boundHashOps(CART + username).delete(skuId);
                return;
            }
            orderItem.setMoney(orderItem.getNum() * orderItem.getPayMoney());
            orderItem.setPayMoney(orderItem.getNum() * orderItem.getPayMoney());
        } else {
            //不存在,新增购物车
            Result<Sku> skuResult = skuFeign.findById(skuId);
            Sku sku = skuResult.getData();
            //getData()
            Spu spu = spuFeign.findSpuById(sku.getSpuId()).getData();
            //将SKU转换成OrderItem
            orderItem = this.sku2OrderItem(sku, spu, num);
        }
        //存入redis
        redisTemplate.boundHashOps(CART + username).put(skuId, orderItem);
    }

  

上一篇:ASP.Net SKU(2)


下一篇:sku算法介绍及实现