ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Redis缓存实例:缓存购物车数据

2020-06-18 23:52:11  阅读:73  来源: 互联网

标签:boundHashOps skuId 缓存 orderItem Redis 购物车 num sku redisTemplate


 

思路:

 

 代码:

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

  

标签:boundHashOps,skuId,缓存,orderItem,Redis,购物车,num,sku,redisTemplate
来源: https://www.cnblogs.com/aaaazzzz/p/13160833.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有