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;
}
再次压测,发现结果正常,只查询了一次数据库
因此,加锁时,思考加锁代码块逻辑很重要 ,上面就是因为锁等待时因为加锁地方不对,头几个线程会处于一种缓存中查询数据为空的阶段,然后当第一个线程执行完保存数据
到缓存后后面进来的线程才会从缓存中获取数据,这也就是出现多次从数据库中查询的原因了