一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、配置
application.properties
spring.cache.type=redis
三、测试使用缓存
- 启动类上开启缓存功能
@EnableCaching
- 只需要使用注解就能完成缓存操作
// 每一个需要缓存的数据我们都来指定要放到哪个名字的缓存【缓存的分区(按照业务类型分)】
@Cacheable({"category"}) // 代表当前方法的结果需要缓存,如果缓存中有,方法不调用。如果缓存中没有,会调用方法
@Override
public List<CategoryEntity> getLevel1Categorys() {
System.out.println("getLevel1Categorys...");
List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
return categoryEntities;
}
访问了两次接口,只打印了一次getLevel1Categorys,说明缓存中有,方法不调用
-
默认行为
○ 如果缓存中有,方法不再调用
○ key是默认生成的:缓存的名字::SimpleKey::
○ 缓存的value值,默认使用jdk序列化机制,将序列化的数据存到redis中
○ 默认时间是 -1 -
自定义操作:key的生成
○ 指定生成缓存的key:key属性指定,接收一个Spel(Spring Expression Language)
- key若为常量要加单引号,如下
-@Cacheable(value = {"category"}, key = "'level1Categorys'")
- SPEL官方文档
- SPEL中文文档
- eg:@Cacheable(value = {"category"}, key = "#root.method.name")
○ 指定缓存的数据的存活时间:配置文件中修改存活时间
-spring.cache.redis.time-to-live=360000
○ 将数据保存为json格式
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
// @Autowired
// public CacheProperties cacheProperties;
/**
* 配置文件的配置没有用上
* @return
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// config = config.entryTtl();
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
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;
}
}
其他的一些配置
#如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true
#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true
@CacheEvict
@CacheEvit就是失效模式:更改数据库缓存就删除
若想一次删除多个缓存,可以 ↓
也可以 ↓
@CachePut就是双写模式:更改数据库的同时也往缓存中存一下