一: 概述
1. 概念
springCache是Spring框架为了简化几种缓存技术的使用繁琐问腿,设定的整合规范。Redis、concurrentHashMap、MongoDB等不同缓存技术
只需要使用相应的cacheManager即可。
2. cacheManager
2.1 接口
public interface CacheManager {
// 缓存管理器管理的某个缓存
@Nullable
Cache getCache(String var1);
// 缓存管理器管理的所有缓存
Collection<String> getCacheNames();
}
2.2 实现
cacheManager的实现类 |
---|
3. 整合
3.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
3.2 配置
spring.cache.type=redis
3.3 注解
@Cacheable: 把数据保存到缓存
@CacheEvict:把数据从缓存中删除
@CachePut:更新缓存
@Caching:组合上面的多个表操作
@CacheConfig:在类级别共享缓存的相同配置
@Cacheable(value="kk",key="kk") & @CacheEvict(value="kk",key="kk") 组合使用达到(失效模式)更新缓存的目的
@Cacheable(value="kk",key="kk") & @CachePut(value="kk",key="kk") 组合使用达到(双写模式)更新缓存的目的
3.4 使用
// 注解的作用:如果第一次请求缓存中没有数据会把数据添加到缓存;如果第二次请求数据直接返回缓存中的数据
@Cacheable(value = "student")
public String testCache() {
// 查询数据库
List<Object> list = mapper.selectByName(name);
return "list";
}
3.5 注解配置项
// 1. 指定缓存的key
@Cacheable(key = "'product'")
// 配置文件
// 2. 指定缓存的过期时间
spring.cache.redis.time-to-live=100000
// 3. 缓存的前缀,不配置默认使用@cacheable()的value值
spring.cache.redis.key-prefix="cache_"
// 4. 是否使用前缀,如果配置为false,缓存的不加任何前缀
spring.cache.redis.use-key-prefix=false
// 5. 是否缓存null值
spring.cache.redis.cache-null-values=true
3.6 自定义缓存管理器配置
自定义配置类
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
public class MyRedisCacheConfiguration {
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 修改value的序列化方式
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
3.7 SpringCache配置
- 穿透问题
SpringCache在解决缓存穿透的问题上,使用了缓存null值的策略
// 5. 是否缓存null值
spring.cache.redis.cache-null-values=true
- 击穿问题
缓存击穿的解决:启用同步机制;不同于分布式锁,springCache是本地锁
@cacheable(sync="true")