IDEA 使用redis 缓冲案列

 1  获取对象数据 


    // 缓存击穿 案列 防止多人同时间访问数据库
    private Goods getGoods(int id){
        // 缓存对象
        Goods goods = (Goods) redisTemplate.opsForValue().get("goods:" + id);
        if (goods==null){
            // 当不存在数据时 设置互斥锁
            Boolean b = redisTemplate.opsForValue().setIfAbsent(RedisContent.REDIS_LOCK, 1);
            if (b){
                // 第一个人 设置成功查询数据
                 goods = service.selectGoodById(id);
                // 缓冲数据 设置1天失效
                redisTemplate.opsForValue().set("goods:" + id,goods,1, TimeUnit.DAYS);
                // 释放锁
                redisTemplate.delete(RedisContent.REDIS_LOCK);
            }else {
                try {
                    // 其它人等待2秒 然后重新调用方法 获取数据
                    Thread.sleep(2000);
                    getGoods(id);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        // 如果不为空 返回对象
        return  goods;
    }

2 三级联动 缓存数据


    @ResponseBody
    @RequestMapping("getCityList")
    public List<City> getCityList(int pid){
        if (redisTemplate.hasKey("citys:"+pid)){
            // 从缓存数据取值
            return  redisTemplate.opsForList().range("citys:"+pid,0,-1);
        }else {
            // 第一次调用方法获取数据
            List<City> cities = service.listCity(pid);
            redisTemplate.opsForList().rightPushAll("citys:"+pid,cities);
            return cities;
        }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值