引入依赖
spring-boot-starter-data-redis
spring-boot-starter-cache
spring.cache.redis.time-to-live=3600000 #如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true #是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true
第四步:使用注解
@Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//将配置文件中所有的配置都生效
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
* 4、Spring-Cache的不足之处: * 1)、读模式 * 缓存穿透:查询一个null数据。解决方案:缓存空数据 * 缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题 * 缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间 * 2)、写模式:(缓存与数据库一致) * 1)、读写加锁。 * 2)、引入Canal,感知到MySQL的更新去更新Redis * 3)、读多写多,直接去数据库查询就行 * 总结: * 常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了) * 特殊数据:特殊设计 ** 原理: * CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写 * * @return */
@CacheEvict触发将缓存数据删除操作(失效模式)
@CacheEvic(value = {"category"}, key = "#root.method.name")
//allEntries =true 删除catagory区域所有缓存数据
@CacheEvict(value = {"catagory"},allEntries = true)
@CachePut不影响方法执行更新缓存(双写模式)
@Caching组合多个操作
@Caching(evict={
@CacheEvic(value = {"category"}, key = "#root.method.name"),
@CacheEvic(value = {"category"}, key = "#root.method.name"))
}
@CacheConfig在类级别共享缓存的相同配置



