1、导入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、启动类开启@EnableCaching
3、在返回的集合方法上加 @Cacheable
如果缓存中有,不调用此方法,反之调用
@Cacheable({“category”}):代表分区
4 、配置文件加spring.cache.type=redis
5、效果,key自动生成的
6、 自定义配置
方法上配置 key : @Cacheable(value = {"category"},key = "'level1Categorys'"):指定key
方法上配置 key : @Cacheable(value = {"category"},key = "#root.method.name"):拿到当前方法信息作为key,支持SPEL表达式,具体看注解内部注释
配置文件中配置过期时间;
cache:
type: redis
redis:
time-to-live: 60000
7、自定义缓存的自动配置
CacheAutoConfiguration->RedisCacheConfiguration
给容器中放一个redisCacheConfiguration,没有用的默认的RedisCacheConfiguration.defaultCacheConfig();
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {
@Autowired
CacheProperties cacheProperties;
@Bean
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
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;
}
}
yaml配置
cache:
type: redis
redis:
time-to-live: 60000
use-key-prefix: false
key-prefix: fuyu
# 缓存空值,可防止穿透
cache-null-values: true
注:使用了前缀,原来的注解的分区key则不生效
8、删除缓存@CacheEvict,一般放在关联数据的修改方法上
@CacheEvict(value = {"category"}, key = "'getLevel1Categorys'")
多个删除:
@Caching(evict = {
@CacheEvict(value = {"category"}, key = "'getLevel1Categorys1'"),
@CacheEvict(value = {"category"}, key = "'getLevel1Categorys2'")
})
删除该分区所有key:
@CacheEvict(value = {“category”}, allEntries=true)