cool hit counter Shopping cart principle and implementation_Intefrankly

Shopping cart principle and implementation


   Today, I simulated the principle of Jingdong's shopping cart implementation to complete the development of the shopping cart module, and share it with you.

Jingdong's shopping cart implementation principle: in the user login and non-login state of the shopping cart into the cookie or persistent to the implementation of redis. Here's how the shopping cart is implemented

Two scenarios.

User login, shopping cart stored in redis

User is not logged in, cart is stored in cookie

Compare the advantages and disadvantages of the two approaches.

 cookie: advantages: data is saved in the user's browser, does not occupy server-side memory; user body check effect is good; code implementation is simple

      Cons: Only 4k of storage space for cookies; cart information does not sync when changing devices; cookies disabled, no saving available

  redis: advantages: data can persist; implements shopping cart synchronization

     Cons: Increased strain on database, slow

Let's start with the implementation idea of using cookies to store shopping carts

1、When the user is not logged in, the user adds a shopping cart and first queries the list of products in the shopping cart from the cookie

2、 Determine if there is information about the product to be added in the product list of the cookie

3. If the cookie has information about the item, add up the number of items

4. If not, check the product information according to the id value of the product

5、Add the products to the shopping cart list

6、Write the shopping cart list into a cookie, set the cookie expiration time

7. Return the cookie to the client.

Shopping cart implementation.

Here the subtotal of the shopping item and the total amount of the shopping cart are calculated in the page using the item directly as the shopping item object

package nyist.e3.pojo;

import java.io.Serializable;
import java.util.Date;

public class TbItem implements Serializable{
    private Long id;

    private String title;

    private String sellPoint;

    private Long price;

    private Integer num;// Number of items purchased as shopping items

    private String barcode;

    private String image;// Show pictures from shopping items

    private Long cid;

    private Byte status;

    private Date created;

    private Date updated;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getSellPoint() {
        return sellPoint;
    }

    public void setSellPoint(String sellPoint) {
        this.sellPoint = sellPoint == null ? null : sellPoint.trim();
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getBarcode() {
        return barcode;
    }

    public void setBarcode(String barcode) {
        this.barcode = barcode == null ? null : barcode.trim();
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image == null ? null : image.trim();
    }

    public Long getCid() {
        return cid;
    }

    public void setCid(Long cid) {
        this.cid = cid;
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}

Code for adding a shopping cart in a cookie:

@Controller
public class ShopCartController {

    @Autowired
    private TbItemService tbItemService;

    @Autowired
    private ShopCartService shopCartService;
     // Get the expiration time
    @Value("${EXPIRE_KEY}")
    private Integer EXPIRE_KEY;

    @Value("${CART_COOKIE}")
    private String CART_COOKIE;

    /**
      * Requirement: Add products to the shopping cart without logging in state, add the shopping over to the cookie
     * 
      * Analysis: 1. Get the shopping cart information from the cookie
      * 2, determine the goods in the shopping cart, if the added goods exist, the number of sums, does not exist, according to the product id query product information, add to the cookie
      * 3、Write the shopping cart list information into the cookie
     * 
     * 
     * @param itemId
     * @param num
     * @return
     */
    @RequestMapping("/cart/add/{itemId}")
    public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue = "1") Integer num,
            HttpServletRequest request, HttpServletResponse response) {
      // 1. Get the shopping cart list
        List<TbItem> itemList = getCartItemList(request);
         // A sign used to determine the existence of goods
        boolean flag = false;
         // 2. Loop through the product information in the list
        for (TbItem tbItem : itemList) {
             // 3. Determine if the added product exists
            if (tbItem.getId() == itemId.longValue()) {
                 // 4. The added item exists in the cookie, add up the quantity
                tbItem.setNum(tbItem.getNum() + num);
                 // Reset labels
                flag = true;
                 // Jump out of the loop
                break;
            }
        }
        if (!flag) {
             // Product information not added in the cookie
             // Search for product information by product id
            TbItem item = tbItemService.getItemById(itemId);
            item.setNum(num);
            if (StringUtils.isNotBlank(item.getImage())) {
                 // Take an image for display use
                item.setImage(item.getImage().split(",")[0]);
            }
             // Add products to cart
            itemList.add(item);
        }
         // write the shopping cart to a cookie
        
        CookieUtils.setCookie(request, response, CART_COOKIE, JsonUtils.objectToJson(itemList),EXPIRE_KEY,true);
        
        return "cartSuccess";

    }


}

Query cart list in cookie.

Thoughts.

1, according to the cookie's name value directly out of the product list information

2、Add the shopping cart list to the mod, return the logical view

private List<TbItem> getCartItemList(HttpServletRequest request) {
         // Use utf-8, you need to set the third parameter to true
        String json = CookieUtils.getCookieValue(request, CART_COOKIE, true);
        if (StringUtils.isNotBlank(json)) {
             // Returns the set of data retrieved from the cookie
            return JsonUtils.jsonToList(json, TbItem.class);
        }
         // Returns an empty collection object
        return new ArrayList<>();
    }



@RequestMapping("/cart/cart")
    public String getCartList(HttpServletRequest request, HttpServletResponse response, Model model) {
         // retrieving product information from a cookie.
        List<TbItem> itemList = getCartItemList(request);
         // Return shopping cart information to the page
        model.addAttribute("cartList", itemList);
         // Jump to logical view
        return "cart";
    }

Function in cookie to delete items from the shopping cart.

1、Receive the SPL id value passed by the page

2. Take the shopping cart list from the cookie, iterate through the loop, and then compare the information of each product traversed with the product to be deleted

3. Remove the item from the shopping cart list if it exists

4. Re-write the shopping cart list to the cookie

5、Response the cookie information to the client

@RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request, HttpServletResponse response) {
        List<TbItem> list = getCartItemList(request);
        for (TbItem tbItem : list) {
            if (tbItem.getId() == itemId.longValue()) {
                list.remove(tbItem);
                break;
            }
        }
         // After successful deletion, the cart list is written to a cookie
        CookieUtils.setCookie(request, response, CART_COOKIE, JsonUtils.objectToJson(list), EXPIRE_KEY, true);

         // After successful deletion, it redirects to the shopping cart list page
        return "redirect:/cart/cart.html";

    }

Adding, querying and deleting of the cookie shopping cart have been implemented, and the process of changing and deleting methods is basically the same.

Implementation of redis shopping cart in login state

Implementing the redis shopping cart add function

Thoughts.

1. Retrieve the login user's information from the request field

2、useredis Store Cart List useredis hit the targethash data type hash ofkey Using the logged-in userid happen to,field ofkey Use of goods ofid happen to, Information about the merchandise asfield ofvalue happen to

3、Complete the cookie to store the shopping cart list

Implemented code.

@Override
    public E3Result addCart(Long userId, Long itemId, Integer num) {
        try {
             // Take the cart from redis and determine if there are already shopping items
            Boolean hexists = jedisClient.hexists(CART_REDIS_KEY_PRE + ":" + userId + "", itemId + "");
            if (hexists) {
                 // Indicates that the item is already in the cart, just add up the quantity of the item
                String hget = jedisClient.hget(CART_REDIS_KEY_PRE + ":" + userId + "", itemId + "");
                 // Add up the quantities
                TbItem item = JsonUtils.jsonToPojo(hget, TbItem.class);
                item.setNum(item.getNum() + num);
                 // Put the item back in the cart
                jedisClient.hset(CART_REDIS_KEY_PRE + ":" + userId + "", itemId + "", JsonUtils.objectToJson(item));
                return E3Result.ok();
            }

             // indicates that there is no information about the product to be added in the shopping cart
             // Look up information about an item based on its id
            TbItem item = itemMapper.selectByPrimaryKey(itemId);
            item.setNum(num);
            if (StringUtils.isNotBlank(item.getImage())) {
                item.setImage(item.getImage().split(",")[0]);
            }
             // Add product information to the shopping cart
            jedisClient.hset(CART_REDIS_KEY_PRE + ":" + userId + "", itemId + "", JsonUtils.objectToJson(item));
            return E3Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return E3Result.build(400, " Product add to cart failed");

    }

Show the list of shopping carts in the logged-in state: need to integrate the shopping cart in the cookie with the shopping cart in redis

1、Take the shopping cart list object from the cookie

2、Fetch the shopping cart object from redis

3、Integrate the shopping cart list in the cookie and the shopping cart list in redis (take out the shopping cart list in the cookie and add it to the redis shopping cart)

5、The final result displayed is based on the shopping cart in redis

/**
      * Shopping cart in cookie and shopping cart in redis for integration
     */
    @Override
    public E3Result mergeCart(Long userId, List<TbItem> itemList) {
        for (TbItem tbItem : itemList) {
             // Just call the add cart business processing logic in the logged-in state
            addCart(userId, tbItem.getId(), tbItem.getNum());
        }
        return E3Result.ok();
    }

Delete shopping items from redis cart

Use the user's id value and the item's id value as the key of hahs and the key of field, respectively, and call hdel(String key,String... field) to complete the deletion function

/**
      * Delete Cart
     * 
     * @return
     * 
     */
    @Override
    public E3Result deleteCartItem(Long id, Long itemId) {
        Long hdel = jedisClient.hdel(CART_REDIS_KEY_PRE + ":" + id + "", itemId + "");
        System.out.println(" Delete cart shopping items as"+hdel);
        return E3Result.ok();
    }

Update the number of purchased items in the redis shopping cart

    /**
* Update the number of items in the shopping cart
     */
    @Override
    public E3Result updateRedisNum(Long id, Long itemId, Integer num) {
         // Retrieve information about the item whose quantity needs to be changed
        String hget = jedisClient.hget(CART_REDIS_KEY_PRE + ":" + id + "", itemId + "");
         // Convert the retrieved json data to commodity objects and then update the quantity
        TbItem item = JsonUtils.jsonToPojo(hget, TbItem.class);
        item.setNum(num);
         // After successful update, write data to redis cart
        jedisClient.hset(CART_REDIS_KEY_PRE + ":" + id + "", itemId + "", JsonUtils.objectToJson(item));
        return E3Result.ok();
    }

When the user clicks go to checkout: jumps to the order confirmation page

1、Generate order details

2、Delivery address information

3、Select the payment method

Before confirming the order, you should determine whether the user is logged in or not, which can be done using an interceptor

1, custom interceptor to implement HandlerInteceptor interface

2. go token message from cookie (token for login authentication)

3, determine whether the value of the token is empty, if empty, jump to the user login page to complete the login, while the current address bar url needs to be passed as a parameter (in the business logic of the login, receive the url, after completing the login, jump to the page)

4, if the token is not empty, according to the token query user information, and then write the user information in the request field, the interceptor to perform the release operation

5, at this time to get the shopping cart list is read from redis and cookie integration of the latest shopping cart.

Interceptor implementation process.

public class LoginInterceptor implements HandlerInterceptor {
    
    @Value("${TT_TOKEN}")
    private String TT_TOKEN;
    @Value("${SSO_LOGIN_URL}")
    private String SSO_LOGIN_URL;
    
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
         // Execute this method before executing the Handler
         // a) Take the token from the cookie.
        String token = CookieUtils.getCookieValue(request, TT_TOKEN);
        if (StringUtils.isBlank(token)) {
             // take the url of the current request
            String url = request.getRequestURL().toString();
             // b) No token, need to jump to the login page.
            response.sendRedirect(SSO_LOGIN_URL + "?redirectUrl=" + url);
             //Interception
            return false;
        }
         // c) have token. Call the sso system's service to query the user information based on the token.
        e3Result result = userService.getUserByToken(token);
        if (result.getStatus() != 200) {
             // d) If the user information is not found. The user login has expired. Need to jump to the login page.
             // take the url of the current request
            String url = request.getRequestURL().toString();
             // b) No token, need to jump to the login page.
            response.sendRedirect(SSO_LOGIN_URL + "?redirectUrl=" + url);
             //Interception
            return false;
        }
         // e) The user information is queried. Release.
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
         // Before returning to ModelAndView after executing Handler

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
         // After returning ModelAndView, execute. Exception Handling.

    }

}





After the interceptor is defined, it needs to be configured in springmvc

<mvc:interceptors>
        <mvc:interceptor>
            <!--  Intercepting all requests -->
            <mvc:mapping path="/**" />
            <!--  Registering Custom Interceptors -->
            <bean class="nyist.e3.interceptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

Receive the url on the login page to implement the sso system callback The redirectUrl received is the parameter passed to the login page in the interception request

So far: the functionality of the shopping cart module is basically implemented, I hope you can correct me if there are any mistakes.


Recommended>>
1、Book Review of Dreams of Ebbs
2、How the Blockchain 30 Era is Leading the Art Market
3、Eurochain OracleChain CEO Old Wolf talks about EOS Super Nodes
4、New Program Hope OpenGL Full Analysis One Opengl Environment Construction
5、Chengdus strongest brain Tianfu Brain and Neurological Research Institute international brain information platform settled in Tianfu New Area

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号