day102-缓存-缓存使用-加锁解决缓存击穿问题以及加锁位置的重要性

1.加锁

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //先从缓存中尝试获取,若为空则从数据库中获取然后放入缓存
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String catalogJson = opsForValue.get("catalogJson");
        System.out.println("从缓存内查询...");
        synchronized (this) {
            if (StringUtils.isEmpty(catalogJson)) {
                Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
                System.out.println("从数据库内查询...");
                String str = JSON.toJSONString(catalogJsonFromDb);
                opsForValue.set("catalogJson", str, 1, TimeUnit.DAYS);
                return catalogJsonFromDb;
            }
        }

        Map<String, List<Catelog2Vo>> catalogJsonFromCache = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return catalogJsonFromCache;
    }

压力测试

为什么呢?后面会说

2.加锁逻辑改良

改良下,把从缓存中获取数据也加入锁逻辑中

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //先从缓存中尝试获取,若为空则从数据库中获取然后放入缓存
        String catalogJson;
        synchronized (this) {
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            catalogJson = opsForValue.get("catalogJson");
            System.out.println("从缓存内查询...");
            if (StringUtils.isEmpty(catalogJson)) {
                Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
                System.out.println("从数据库内查询...");
                String str = JSON.toJSONString(catalogJsonFromDb);
                opsForValue.set("catalogJson", str, 1, TimeUnit.DAYS);
                return catalogJsonFromDb;
            }
        }

        Map<String, List<Catelog2Vo>> catalogJsonFromCache = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return catalogJsonFromCache;
    }

再次压测,发现结果正常,只查询了一次数据库

因此,加锁时,思考加锁代码块逻辑很重要 ,上面就是因为锁等待时因为加锁地方不对,头几个线程会处于一种缓存中查询数据为空的阶段,然后当第一个线程执行完保存数据

到缓存后后面进来的线程才会从缓存中获取数据,这也就是出现多次从数据库中查询的原因了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我才是真的封不觉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值