redis 实现购物车

2018-06-13  本文已影响0人  乘以零

购物车列表页 分店铺 商品 购买属性 具体的数据

{ 
   sellerId:{ 
       productId:{
         productProperty : CartVo
       } 
    } 
}

基础数据 Cart 存购物车

cart.png

详细数据 CartVo (在cart的基础上加上 shopName productName等相关数据)存Redis

redis 存放方式

        Long createTime = cart.getCreateTime();
        String buyerToSellerKey = buyerToSellerKey(buyerId);

        // sellerId作分页用
        redisTemplate.opsForZSet().add(buyerToSellerKey, sellerId, createTime);
        // redisTemplate.opsForZSet().remove(buyerToSellerKey, sellerId);

        // 把buyerId sellerId 对应 cartIds cartVo 存入redis
        String buyerSellerToIdVoKey = this.buyerSellerToIdVoKey(buyerId, sellerId);
        CartVo cartVo = null;// 封装好cartVo
        redisTemplate.opsForHash().put(buyerSellerToIdVoKey, cart.getId(), cartVo);
        // redisTemplate.opsForHash().delete(buyerSellerToIdVoKey,
        // cart.getId());

购物车列表显示时 先按照buyerId分页

    /**
     * 
     * @param buyerId
     * @param currPage
     * @param pageSize
     * @return
     * 
     *         <pre>
     * { 
     *   sellerId:{ 
     *     productId:{
     *       productProperty : CartVo
     *     } 
     *   } 
     * }
     *         </pre>
     */
    public Map<String, Map<Long, Map<String, CartVo>>> page(String buyerId, Integer currPage, Integer pageSize) {
        String buyerToSellerKey = buyerToSellerKey(buyerId);
        Pager<?> pager = new Pager<>(currPage, pageSize);
        Set<Object> sellerIds = redisTemplate.opsForZSet().reverseRange(buyerToSellerKey,
                pager.getFirstResult(), pager.getLastResult() - 1);

        Map<String, Map<Long, Map<String, CartVo>>> value = new HashMap<>();

        for (Object obj : sellerIds) {
            String sellerId = String.valueOf(obj);
            String buyerSellerToIdVoKey = this.buyerSellerToIdVoKey(buyerId, sellerId);
            Set<Object> cartIds = this.redisTemplate.opsForHash().keys(buyerSellerToIdVoKey);
            List<Object> cartVos = this.redisTemplate.opsForHash().multiGet(buyerSellerToIdVoKey, cartIds);
            for (Object cartVoObj : cartVos) {
                CartVo cartVo = (CartVo) cartVoObj;
                Long productId = cartVo.getProductId();
                String productProperty = cartVo.getProductProperty();

                Map<Long, Map<String, CartVo>> productMap = value.get(sellerId);
                if (productMap == null) {
                    productMap = new HashMap<>();
                }

                Map<String, CartVo> propertyMap = productMap.get(productId);
                if (propertyMap == null) {
                    propertyMap = new HashMap<>();
                }
                propertyMap.put(productProperty, cartVo);
                productMap.put(productId, propertyMap);
                value.put(sellerId, productMap);
            }
        }

        return value;
    }
上一篇下一篇

猜你喜欢

热点阅读