版权声明:柠檬乐园:200145783 https://blog.csdn.net/u014431237/article/details/81914837
Springboot 整合Redis,缓存过期之后,如果多个线程同时请求对某个数据的访问,会同时去到数据库,导致数据库瞬间负荷增高。
解决办法:
①Spring4.3为@Cacheable注解提供了一个新的参数“sync”(boolean类型,缺省为false),当设置它为true时,只有一个线程的请求会去到数据库,其他线程都会等待直到缓存可用。这个设置可以减少对数据库的瞬间并发访问。
@Cacheable(sync=true)
②使用RedisTemplate 来设置缓存
// 注入springboot自动配置的
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Override
public List<User> selectAll() {
//字符串的序列化器 默认utf8
RedisSerializer resdisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(resdisSerializer);
List<User> list = (List<User>) redisTemplate.opsForValue().get("users");
//双重检测锁
if (null == list) {
synchronized (this) {
list = (List<User>) redisTemplate.opsForValue().get("users");
if (null == list) {
list = userMapper.selectAll();
System.out.println("查询了数据库----------");
redisTemplate.opsForValue().set("users", list);
}else{
System.out.println("使用了缓存");
}
}
}else{
System.out.println("使用了缓存");
}
return list;
}