@Servicepublic class CartServiceImpl implementsCartService {private static final String CART="Cart_";
@AutowiredprivateRedisTemplate redisTemplate;
@AutowiredprivateSkuFeign skuFeign;
@AutowiredprivateSpuFeign spuFeign;/*** 添加购物车
*@paramskuId
*@paramnum*/@Overridepublic voidadd(String skuId, Integer num,String username) {/*** 1)查询redis中的数据
* 2)如果redis中已经有了,则追加数量,重新计算金额
* 3)如果没有,将商品添加到缓存*/OrderItem orderItem= (OrderItem)redisTemplate.boundHashOps(CART+username).get(skuId);//从redis中取值if (orderItem != null){//存在,刷新购物车
orderItem.setNum(orderItem.getNum()+num);
orderItem.setMoney(orderItem.getNum()*orderItem.getPrice());
orderItem.setPayMoney(orderItem.getNum()*orderItem.getPrice());
}else{//不存在,新增购物车
Result skuResult =skuFeign.findById(skuId);
Sku sku=skuResult.getData();
Spu spu=spuFeign.findByspuId(sku.getSpuId());//将SKU转换成OrderItem
orderItem = this.sku2OrderItem(sku,spu,num);
}//存入redis
redisTemplate.boundHashOps(CART+username).put(skuId,orderItem);//往redis中存值
}//sku转换为orderItem
privateOrderItem sku2OrderItem(Sku sku, Spu spu, Integer num) {
OrderItem orderItem= newOrderItem();
orderItem.setSpuId(sku.getSpuId());
orderItem.setSkuId(sku.getId());
orderItem.setName(sku.getName());
orderItem.setPrice(sku.getPrice());
orderItem.setNum(num);
orderItem.setMoney(num*orderItem.getPrice()); //单价*数量
orderItem.setPayMoney(num*orderItem.getPrice()); //实付金额
orderItem.setImage(sku.getImage());
orderItem.setWeight(sku.getWeight()*num); //重量=单个重量*数量//分类ID设置
orderItem.setCategoryId1(spu.getCategory1Id());
orderItem.setCategoryId2(spu.getCategory2Id());
orderItem.setCategoryId3(spu.getCategory3Id());returnorderItem;
}
}