@Autowired
private RedisTemplate<Object, Object> redisTemplate;
/**
* 双重检测加同步代码块的实现
* @return java.lang.Double
* @author SongXiaTongZi
* @description
* @date 2019/8/13
* @method queryHistoryAverageRate
**/
@Override
public Double queryHistoryAverageRate() {
//设置redis模板对象的序列化方式 (需要接口的实现类) 可以让key的值不是二进制数
redisTemplate.setKeySerializer(new StringRedisSerializer());
//首先去缓存中获取,
//缓存中没有的话,去数据库中查询
//将查询的数据存放到redis数据库中
//将常用的字符串改成常量值,便于使用 Constants.HISTORY_AVERAGE_RATE
Double historyAverageRate = (Double) redisTemplate.opsForValue().get(Constants.HISTORY_AVERAGE_RATE);
if (historyAverageRate == null) {
synchronized (this) {
historyAverageRate = (Double) redisTemplate.opsForValue().get(Constants.HISTORY_AVERAGE_RATE);
if (historyAverageRate == null) {
//去数据库中查询
historyAverageRate = loanInfoMapper.selectHistoryAverageRate();
//将查询好的数据存到redis缓存中
//return ValueOperations<K, V>
//设置失效时间
//Long
//将查询结果放进redis中
//Constants 常量的类名
redisTemplate.opsForValue().set(Constants.HISTORY_AVERAGE_RATE, historyAverageRate, 15, TimeUnit.MINUTES);
System.out.println("从mysql数据库中查询");
} else {
System.out.println("从redis中获取");
}
}
} else {
System.out.println("从redis中获取");
}
return historyAverageRate;
}
双重检测加同步代码块(解决缓存穿透的问题)
猜你喜欢
转载自blog.csdn.net/FOGUANGPUZHAOFOFA/article/details/101640494
今日推荐
周排行