缓存穿透指的是一个缓存系统无法缓存某个查询的数据,从而导致这个查询每一次都要访问数据库。
常见的Redis缓存穿透场景包括:
使用Guava在内存中维护一个布隆过滤器
com.google.guava guava 29.0-jre
org.springframework.boot spring-boot-starter-data-redis
缓存中维护Bloom Filter
public class BloomFilterUtil {// 布隆过滤器的预计容量private static final int expectedInsertions = 1000000;// 布隆过滤器误判率private static final double fpp = 0.001;private static BloomFilter bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, fpp);/*** 向Bloom Filter中添加元素*/public static void add(String key){bloomFilter.put(key);}/*** 判断元素是否存在于Bloom Filter中*/public static boolean mightContain(String key){return bloomFilter.mightContain(key);}
}
在Controller中查询数据时,先根据请求参数进行Bloom Filter的过滤
@Autowired
private RedisTemplate redisTemplate;@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id){// 先从布隆过滤器中判断此id是否存在if(!BloomFilterUtil.mightContain(id.toString())){return null;}// 查询缓存数据String userKey = "user_"+id.toString();User user = (User) redisTemplate.opsForValue().get(userKey);if(user == null){// 查询数据库user = userRepository.findById(id).orElse(null);if(user != null){// 将查询到的数据加入缓存redisTemplate.opsForValue().set(userKey, user, 300, TimeUnit.SECONDS);}else{// 查询结果为空,将请求记录下来,并在布隆过滤器中添加BloomFilterUtil.add(id.toString());}}return user;
}
缓存击穿指的是在一些高并发访问下,一个热点数据从缓存中不存在,每次请求都要直接查询数据库,从而导致数据库压力过大,并且系统性能下降的现象。
缓存击穿的原因通常有以下几种:
在遇到缓存击穿问题时,我们可以在查询数据库之前,先判断一下缓存中是否已有数据,如果没有数据则使用Redis的单线程特性,先查询数据库然后将数据写入缓存中。
org.springframework.boot spring-boot-starter-data-redis
先从缓存中查询数据,如果缓存中无数据则进行锁操作
@Autowired
private RedisTemplate redisTemplate;@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id){// 先从缓存中获取值String userKey = "user_"+id.toString();User user = (User) redisTemplate.opsForValue().get(userKey);if(user == null){// 查询数据库之前加锁String lockKey = "lock_user_"+id.toString();String lockValue = UUID.randomUUID().toString();try{Boolean lockResult = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 60, TimeUnit.SECONDS);if(lockResult != null && lockResult){// 查询数据库user = userRepository.findById(id).orElse(null);if(user != null){// 将查询到的数据加入缓存redisTemplate.opsForValue().set(userKey, user, 300, TimeUnit.SECONDS);}}}finally{// 释放锁if(lockValue.equals(redisTemplate.opsForValue().get(lockKey))){redisTemplate.delete(lockKey);}}}return user;
}
缓存中大量数据的失效时间集中在某一个时间段,导致在这个时间段内缓存失效并额外请求数据库查询数据的请求大量增加,从而对数据库造成极大的压力和负荷
添加相关依赖
org.springframework.boot spring-boot-starter-data-redis
net.sf.ehcache ehcache 2.10.6
application.properties中配置Ehcache缓存
spring.cache.type=ehcache
创建一个CacheConfig类,用于配置Ehcache
@Configuration
@EnableCaching
public class CacheConfig {@Beanpublic EhCacheCacheManager ehCacheCacheManager(CacheManager cm){return new EhCacheCacheManager(cm);}@Beanpublic CacheManager ehCacheManager(){EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));cmfb.setShared(true);return cmfb.getObject();}
}
在ehcache.xml中添加缓存配置
先从Ehcache缓存中获取,如果缓存中无数据则再从Redis缓存中获取数据
@Autowired
private RedisTemplate redisTemplate;@Autowired
private CacheManager ehCacheManager;@GetMapping("/user/{id}")
@Cacheable(value = "userCache", key = "#id")
public User getUserById(@PathVariable Long id){// 先从Ehcache缓存中获取String userKey = "user_"+id.toString();User user = (User) ehCacheManager.getCache("userCache").get(userKey).get();if(user == null){// 再从Redis缓存中获取user = (User) redisTemplate.opsForValue().get(userKey);if(user != null){ehCacheManager.getCache("userCache").put(userKey, user);}}return user;
}