1. 程式人生 > >購物車實現及原理(仿京東實現原理)

購物車實現及原理(仿京東實現原理)

關於購物車的東西, 這裡首先丟擲四個問題:

1)使用者沒登陸使用者名稱和密碼,新增商品, 關閉瀏覽器再開啟後 不登入使用者名稱和密碼 問:購物車商品還在嗎? 

2)使用者登陸了使用者名稱密碼,新增商品,關閉瀏覽器再開啟後 不登入使用者名稱和密碼 問:購物車商品還在嗎?   

3)使用者登陸了使用者名稱密碼,新增商品, 關閉瀏覽器,然後再開啟,登陸使用者名稱和密碼  問:購物車商品還在嗎?

4)使用者登陸了使用者名稱密碼,新增商品, 關閉瀏覽器 外地老家開啟瀏覽器  登陸使用者名稱和密碼 問:購物車商品還在嗎?

上面四個問題都是以京東為模板, 那麼大家猜猜結果是什麼呢?
1)在
2)不在了
3)在
4)在

如果你能夠猜到答案, 那麼說明你真的很棒, 那麼關於這四點是怎麼實現的呢? (如果有不認可的小夥伴可以用京東實驗一下)
下面我們就來講解下購物車的原理,最後再來說下具體的code實現.
1)使用者沒有登入, 新增商品, 此時的商品是被新增到了瀏覽器的Cookie中, 所以當再次訪問時(不登入),商品仍然在Cookie中, 所以購物車中的商品還是存在的.
2)使用者登入了,新增商品, 此時會將Cookie中和使用者選擇的商品都新增到購物車中, 然後刪除Cookie中的商品. 所以當用戶再次訪問(不登入),此時Cookie中的購物車商品已經被刪除了, 所以此時購物車中的商品不在了.
3)使用者登入, 新增商品,此時商品被新增到資料庫做了持久化儲存, 再次開啟登入使用者名稱和密碼, 該使用者選擇的商品肯定還是存在的, 所以購物車中的商品還是存在的.
4)理由3)

這裡再說下 沒登入 儲存商品到Cookie的優點以及儲存到Session和資料庫的對比:

1:Cookie: 優點: 儲存使用者瀏覽器(不用浪費我們公司的伺服器) 缺點:Cookie禁用,不提供儲存
2:Session:(Redis : 浪費大量伺服器記憶體:實現、禁用Cookie) 速度很快
3:資料庫(Mysql、Redis、SOlr) 能持久化的就資料庫 速度太慢

那麼我今天要講的就是:

使用者沒登陸:購物車新增到Cookie中
使用者登陸: 儲存購物車到Redis中 (不用資料庫)

整體的思路圖解:


接下來就是程式碼例項來實現 購物車的功能了:
首先我們看下購物車和購物項兩個JavaBean的設計:

購物車: buyerCart.java

 public class BuyerCart implements Serializable{
 
     /**
      * 購物車
      */
     private static final long serialVersionUID = 1L;
     
     //商品結果集
     private List<BuyerItem> items = new ArrayList<BuyerItem>();
     
     //新增購物項到購物車
     public void addItem(BuyerItem item){
        //判斷是否包含同款
         if (items.contains(item)) {
             //追加數量
             for (BuyerItem buyerItem : items) {
                if (buyerItem.equals(item)) {
                     buyerItem.setAmount(item.getAmount() + buyerItem.getAmount());
                 }
             }
         }else {
             items.add(item);
         }
         
     }
 
     public List<BuyerItem> getItems() {
         return items;
     }
 
     public void setItems(List<BuyerItem> items) {
         this.items = items;
     }
     
     
     //小計
     //商品數量
     @JsonIgnore
     public Integer getProductAmount(){
         Integer result = 0;
         //計算
         for (BuyerItem buyerItem : items) {
             result += buyerItem.getAmount();
         }
         return result;
     }
     
     //商品金額
     @JsonIgnore
     public Float getProductPrice(){
         Float result = 0f;
         //計算
         for (BuyerItem buyerItem : items) {
             result += buyerItem.getAmount()*buyerItem.getSku().getPrice();
         }
         return result;
     }
     
     //運費
     @JsonIgnore
     public Float getFee(){
         Float result = 0f;
         //計算
         if (getProductPrice() < 79) {
             result = 5f;
         }
         
         return result;
     }
     
     //總價
     @JsonIgnore
     public Float getTotalPrice(){
         return getProductPrice() + getFee();
     }
     
 }

這裡使用了@JsonIgonre註解是因為下面需要將BuyerCart 轉換成Json格式, 而這幾個欄位只有get 方法, 所以不能轉換, 需要使用忽略Json.

下面是購物項: buyerItem.java

public class BuyerItem implements Serializable{
 
     private static final long serialVersionUID = 1L;
 
     //SKu物件
     private Sku sku;
     
     //是否有貨
     private Boolean isHave = true;
     
     //購買的數量
     private Integer amount = 1;
 
     public Sku getSku() {
         return sku;
     }
 
     public void setSku(Sku sku) {
         this.sku = sku;
     }
 
     public Boolean getIsHave() {
         return isHave;
     }
 
     public void setIsHave(Boolean isHave) {
         this.isHave = isHave;
     }
 
     public Integer getAmount() {
         return amount;
     }
 
     public void setAmount(Integer amount) {
         this.amount = amount;
     }
 
     @Override
     public int hashCode() {
         final int prime = 31;
         int result = 1;
         result = prime * result + ((sku == null) ? 0 : sku.hashCode());
         return result;
     }
 
     @Override
     public boolean equals(Object obj) {
         if (this == obj) //比較地址
             return true;
         if (obj == null)
             return false;
         if (getClass() != obj.getClass())
             return false;
         BuyerItem other = (BuyerItem) obj;
         if (sku == null) {
            if (other.sku != null)
                 return false;
         } else if (!sku.getId().equals(other.sku.getId()))
             return false;
         return true;
     }
 }

1,將商品加入購物車中

//加入購物車
 function  addCart(){
       //  + skuId
       window.location.href="/shopping/buyerCart?skuId="+skuId+"&amount="+$("#buy-num").val();
 }

這裡傳入的引數是skuId(庫存表的主鍵, 庫存表儲存的商品id,顏色,尺碼,庫存等資訊), 購買數量amount.

接著我們來看Controller是如何來處理的:

//加入購物車
     @RequestMapping(value="/shopping/buyerCart")
     public <T> String buyerCart(Long skuId, Integer amount, HttpServletRequest request,
             HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException{
         //將物件轉換成json字串/json字串轉成物件
         ObjectMapper om = new ObjectMapper();
         om.setSerializationInclusion(Include.NON_NULL);
         BuyerCart buyerCart = null;
         //1,獲取Cookie中的購物車
         Cookie[] cookies = request.getCookies();
         if (null != cookies && cookies.length > 0) {
             for (Cookie cookie : cookies) {
                 //
                 if (Constants.BUYER_CART.equals(cookie.getName())) {
                     //購物車 物件 與json字串互轉
                     buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
                     break;
                 }
             }
         }
         
         //2,Cookie中沒有購物車, 建立購物車物件
         if (null == buyerCart) {
             buyerCart = new BuyerCart();
         }
         
         //3, 將當前款商品追加到購物車
         if (null != skuId && null != amount) {
             Sku sku = new Sku();
             sku.setId(skuId);
             BuyerItem buyerItem = new BuyerItem();
             buyerItem.setSku(sku);
             //設定數量
             buyerItem.setAmount(amount);
             //新增購物項到購物車
               buyerCart.addItem(buyerItem);
         }
         
         //排序  倒序
         List<BuyerItem> items = buyerCart.getItems();
         Collections.sort(items, new Comparator<BuyerItem>() {
 
             @Override
             public int compare(BuyerItem o1, BuyerItem o2) {
                 return -1;
            }
             
         });
         
         //前三點 登入和非登入做的是一樣的操作, 在第四點需要判斷
         String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
         if (null != username) {
             //登入了
             //4, 將購物車追加到Redis中
             cartService.insertBuyerCartToRedis(buyerCart, username);
             //5, 清空Cookie 設定存活時間為0, 立馬銷燬
             Cookie cookie = new Cookie(Constants.BUYER_CART, null);
             cookie.setPath("/");
             cookie.setMaxAge(-0);
             response.addCookie(cookie);
         }else {
             //未登入
             //4, 儲存購物車到Cookie中
             //將物件轉換成json格式
             Writer w = new StringWriter();
             om.writeValue(w, buyerCart);
             Cookie cookie = new Cookie(Constants.BUYER_CART, w.toString());
             //設定path是可以共享cookie
             cookie.setPath("/");
            //設定Cookie過期時間: -1 表示關閉瀏覽器失效  0: 立即失效  >0: 單位是秒, 多少秒後失 
            //效
             cookie.setMaxAge(24*60*60);
             //5,Cookie寫會瀏覽器
             response.addCookie(cookie);
         }
         
         //6, 重定向
         return "redirect:/shopping/toCart";
     }

這裡設計一個知識點: 將物件轉換成json字串/json字串轉成物件
我們在這裡先寫一個小的Demo來演示json和物件之間的互轉, 這裡使用到了springmvc中的ObjectMapper類.

public class TestJson {
 
     @Test
     public void testAdd() throws Exception {
         TestTb testTb = new TestTb();
         testTb.setName("范冰冰");
         ObjectMapper om = new ObjectMapper();
         om.setSerializationInclusion(Include.NON_NULL);
         //將物件轉換成json字串
         Writer wr = new StringWriter();
         om.writeValue(wr, testTb);
         System.out.println(wr.toString());
         
          //轉回物件
         TestTb r = om.readValue(wr.toString(), TestTb.class);
         System.out.println(r.toString());
     }
     
 }

執行結果: 

這裡我們使用了Include.NON_NULL, 如果TestTb 中屬性為null 的就不給轉換成Json, 從物件-->Json字串  用的是 objectMapper.writeValue(). 從Json字串-->物件使用的是objectMapper.readValue().
迴歸上面我們專案中的程式碼, 只有未登入 新增商品時才會將此商品新增到Cookie中.

//未登入
            //4, 儲存購物車到Cookie中
             //將物件轉換成json格式
             Writer w = new StringWriter();
             om.writeValue(w, buyerCart);
             Cookie cookie = new Cookie(Constants.BUYER_CART, w.toString());
             //設定path是可以共享cookie
             cookie.setPath("/");
             //設定Cookie過期時間: -1 表示關閉瀏覽器失效  0: 立即失效  >0: 單位是秒, 多少秒後失效
             cookie.setMaxAge(24*60*60);
             //5,Cookie寫會瀏覽器
             response.addCookie(cookie);

我們debug 可以看到:

這裡已經將物件購物車物件buyerCart轉換成了Json格式.
將商品新增到購物車, 不管是登入還是未登入, 都要先取出Cookie中的購物車, 然後將當前選擇的商品追加到購物車中.
然後登入的話  就把Cookie中的購物車清空, 並將購物車的內容新增到Redis中做持久化儲存.
如果未登入, 將選擇的商品追加到Cookie中.

將購物車追加到Redis中的程式碼:insertBuyerCartToRedis(這裡麵包含了判斷新增的是否是同款)

//儲存購物車到Redis中
     public void insertBuyerCartToRedis(BuyerCart buyerCart, String username){
         List<BuyerItem> items = buyerCart.getItems();
         if (items.size() > 0) {
             //redis中儲存的是skuId 為key , amount 為value的Map集合
             Map<String, String> hash = new HashMap<String, String>();
             for (BuyerItem item : items) {
                 //判斷是否有同款
                 if (jedis.hexists("buyerCart:"+username, String.valueOf(item.getSku().getId()))) {
                     jedis.hincrBy("buyerCart:"+username, String.valueOf(item.getSku().getId()), item.getAmount());
                 }else {
                     hash.put(String.valueOf(item.getSku().getId()), String.valueOf(item.getAmount()));
                 }
             }
             if (hash.size() > 0) {
                 jedis.hmset("buyerCart:"+username, hash);
             }
         }
         
     }

判斷使用者是否登入: String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));

 public class RequestUtils {
 
    //獲取CSessionID
     public static String getCSessionId(HttpServletRequest request, HttpServletResponse response){
        //1, 從Request中取Cookie
         Cookie[] cookies = request.getCookies();
         //2, 從Cookie資料中遍歷查詢, 並取CSessionID
         if (null != cookies && cookies.length > 0) {
             for (Cookie cookie : cookies) {
                 if ("CSESSIONID".equals(cookie.getName())) {
                     //有, 直接返回
                     return cookie.getValue();
                 }
             }
         }
         //沒有, 建立一個CSessionId, 並且放到Cookie再返回瀏覽器.返回新的CSessionID
         String csessionid = UUID.randomUUID().toString().replaceAll("-", "");
         //並且放到Cookie中
         Cookie cookie = new Cookie("CSESSIONID", csessionid);
         //cookie  每次都帶來, 設定路徑
         cookie.setPath("/");
         //0:關閉瀏覽器  銷燬cookie. 0:立即消失.  >0 存活時間,秒
         cookie.setMaxAge(-1);
         
         return csessionid;
     }
 }
//獲取
     public String getAttributterForUsername(String jessionId){
         String value = jedis.get(jessionId + ":USER_NAME");
         if(null != value){
             //計算session過期時間是 使用者最後一次請求開始計時.
             jedis.expire(jessionId + ":USER_NAME", 60*exp);
             return value;
         }
         return null;
     }

==========================================2,購物車展示頁面

最後 重定向到購物車展示頁: return "redirect:/shopping/toCart"; 這裡進入結算頁有兩種方式:
1) 在商品詳情頁 點選加入購物車.
2) 直接點選購物車按鈕 進入購物車結算頁.

下面來看下結算頁的程式碼:

@Autowired
     private CartService cartService;
     //去購物車結算, 這裡有兩個地方可以直達: 1,在商品詳情頁 中點選加入購物車按鈕  2, 直接點選購物車按鈕
     @RequestMapping(value="/shopping/toCart")
     public String toCart(Model model, HttpServletRequest request,
             HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException{ 
         //將物件轉換成json字串/json字串轉成物件
         ObjectMapper om = new ObjectMapper();
         om.setSerializationInclusion(Include.NON_NULL);
         BuyerCart buyerCart = null;
         //1,獲取Cookie中的購物車
         Cookie[] cookies = request.getCookies();
         if (null != cookies && cookies.length > 0) {
             for (Cookie cookie : cookies) {
                 //
                 if (Constants.BUYER_CART.equals(cookie.getName())) {
                     //購物車 物件 與json字串互轉
                     buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
                     break;
                 }
             }
         }
         
         //判斷是否登入
         String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
         if (null != username) {
             //登入了
             //2, 購物車 有東西, 則將購物車的東西儲存到Redis中
             if (null == buyerCart) {
                 cartService.insertBuyerCartToRedis(buyerCart, username);
                 //清空Cookie 設定存活時間為0, 立馬銷燬
                 Cookie cookie = new Cookie(Constants.BUYER_CART, null);
                 cookie.setPath("/");
                 cookie.setMaxAge(-0);
                 response.addCookie(cookie);
             }
             //3, 取出Redis中的購物車
             buyerCart = cartService.selectBuyerCartFromRedis(username);
         }
         
         
         //4, 沒有 則建立購物車
         if (null == buyerCart) {
             buyerCart = new BuyerCart();
         }
         
         //5, 將購物車裝滿, 前面只是將skuId裝進購物車, 這裡還需要查出sku詳情
         List<BuyerItem> items = buyerCart.getItems();
         if(items.size() > 0){
             //只有購物車中有購物項, 才可以將sku相關資訊加入到購物項中
             for (BuyerItem buyerItem : items) {
                 buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));
             }
         }
         
         //5,上面已經將購物車裝滿了, 這裡直接回顯頁面
         model.addAttribute("buyerCart", buyerCart);
         
         //跳轉購物頁面
         return "cart";
     }

這裡 就是 購物車詳情展示頁面, 這裡需要注意, 如果是同一件商品連續新增, 是需要合併的.
購物車詳情展示頁面就包括兩大塊, 1) 商品詳情 2)總計(商品總額,運費)
其中1)商品詳情又包括 商品尺碼,商品顏色, 商品購買數量, 是否有貨.

取出Redis中的購物車: buyerCart = cartService.selectBuyerCartFromRedis(username);

 //取出Redis中購物車
     public BuyerCart selectBuyerCartFromRedis(String username){
         BuyerCart buyerCart = new BuyerCart();
         //獲取所有商品, redis中儲存的是skuId 為key , amount 為value的Map集合
         Map<String, String> hgetAll = jedis.hgetAll("buyerCart:"+username);
         Set<Entry<String, String>> entrySet = hgetAll.entrySet();
         for (Entry<String, String> entry : entrySet) {
             //entry.getKey(): skuId
             Sku sku = new Sku();
             sku.setId(Long.parseLong(entry.getKey()));
             BuyerItem buyerItem = new BuyerItem();
             buyerItem.setSku(sku);
             //entry.getValue(): amount
             buyerItem.setAmount(Integer.parseInt(entry.getValue()));
             //新增到購物車中
             buyerCart.addItem(buyerItem);
         }
         
         return buyerCart;
     }

將購物車裝滿, 前面只是將skuId裝進購物車, 這裡還需要查出sku詳情: List<BuyerItem> items = buyerCart.getItems();
buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));

//向購物車中的購物項 新增相應的資料, 通過skuId 查詢sku物件, 顏色物件, 商品物件
     public Sku selectSkuById(Long skuId){
         Sku sku = skuDao.selectByPrimaryKey(skuId);
         //顏色
         sku.setColor(colorDao.selectByPrimaryKey(sku.getColorId()));
         //新增商品資訊
         sku.setProduct(productDao.selectByPrimaryKey(sku.getProductId()));
         return sku;
     }

接著就返回"cart.jsp", 這個就是購物車詳情展示頁面了.

================================================3, 去結算頁面
到了這裡就說明使用者必須要 登入, 而且購物車中必須要有商品.
所以這裡我麼你需要利用springmvc的過濾功能, 使用者點選結算的時候必須要先登入, 如果沒有登入的話就提示使用者需要登入.

//去結算
     @RequestMapping(value="/buyer/trueBuy")
     public String trueBuy(String[] skuIds, Model model, HttpServletRequest request, HttpServletResponse response){
         //1, 購物車必須有商品, 
         //取出使用者名稱  再取出購物車
         String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
         //取出所有購物車
         BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds(skuIds, username);
         List<BuyerItem> items = buyerCart.getItems();
         if (items.size() > 0) {
             //購物車中有商品
            //判斷所勾選的商品是否都有貨, 如果有一件無貨, 那麼就重新整理頁面.
             Boolean flag = true;
             //2, 購物車中商品必須有庫存 且購買大於庫存數量時視為無貨. 提示: 購物車原頁面不動. 有貨改為無貨, 加紅提醒.
             for (BuyerItem buyerItem : items) {
                 //裝滿購物車的購物項, 當前購物項只有skuId這一個東西, 我們還需要購物項的數量去判斷是否有貨
                 buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));
                 //校驗庫存
                 if (buyerItem.getAmount() > buyerItem.getSku().getStock()) {
                     //無貨
                     buyerItem.setIsHave(false);
                     flag = false;
                 }
                 if (!flag) {
                     //無貨, 原頁面不動, 有貨改成無貨, 重新整理頁面.
                     model.addAttribute("buyerCart", buyerCart);
                     return "cart";
                 }
             }
         }else {
             //購物車沒有商品
             //沒有商品: 1>原購物車頁面重新整理(購物車頁面提示沒有商品)
             return "redirect:/shopping/toCart";
         }         
         
         //3, 正常進入下一個頁面
         return "order";
     }

取出 所指定的購物車, 因為我們結算之前在購物車詳情頁面會勾選 我們 需要購買的商品, 所以這裡是根據所勾選的商品去結算的.
BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds(skuIds, username);
從購物車中取出指定商品:

//從購物車中取出指定商品
     public BuyerCart selectBuyerCartFromRedisBySkuIds(String[] skuIds, String username){
         BuyerCart buyerCart = new BuyerCart();
         //獲取所有商品, redis中儲存的是skuId 為key , amount 為value的Map集合
         Map<String, String> hgetAll = jedis.hgetAll("buyerCart:"+username);
         if (null != hgetAll && hgetAll.size() > 0) {
             Set<Entry<String, String>> entrySet = hgetAll.entrySet();
             for (Entry<String, String> entry : entrySet) {
                 for (String skuId : skuIds) {
                     if (skuId.equals(entry.getKey())) {
                         //entry.getKey(): skuId
                         Sku sku = new Sku();
                         sku.setId(Long.parseLong(entry.getKey()));
                         BuyerItem buyerItem = new BuyerItem();
                         buyerItem.setSku(sku);
                         //entry.getValue(): amount
                         buyerItem.setAmount(Integer.parseInt(entry.getValue()));
                         //新增到購物車中
                         buyerCart.addItem(buyerItem);
                     }
                 }
             }
         }
         
         return buyerCart;
     }

1) 當我們購買的商品只要有一件是無貨的狀態, 那麼重新整理購物車詳情頁面, 回顯無貨的商品狀態. 
2)當購物車中午商品時, 重新整理當前頁面.

購物車就這麼多東西, 可能講解有不到或者錯誤的地方, 歡迎大家能夠指出來.