思路:

代碼:
@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);
}
