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;
}
再次压测,发现结果正常,只查询了一次数据库

因此,加锁时,思考加锁代码块逻辑很重要 ,上面就是因为锁等待时因为加锁地方不对,头几个线程会处于一种缓存中查询数据为空的阶段,然后当第一个线程执行完保存数据
到缓存后后面进来的线程才会从缓存中获取数据,这也就是出现多次从数据库中查询的原因了

博客讨论了在Java中进行缓存查询时的加锁优化问题。原始代码由于加锁位置不当导致在高并发下多次查询数据库。通过调整加锁逻辑,确保所有线程在读取缓存时都进行加锁,从而避免了不必要的数据库查询,提高了系统的性能。在压力测试中,优化后的代码表现正常,仅查询数据库一次。
2万+

被折叠的 条评论
为什么被折叠?



