整合体验@Cacheable 引入依赖 dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-cache/artifactId/dependencydependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-redis/arti
整合&体验@Cacheable
引入依赖
<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>自动配置 使用redis
application.properties 设置 spring.cache.type=redis缓存注解
@Cacheable triggers cache population //触发将数据保存到缓存的操作 @CacheEvict triggers cache eviction //触发将数据从缓存删除的操作 @CachePut updates the cache without interfering with the method execution //不影响方法执行更新缓存 @Caching regroups multiple cache operations to be applied on a method //组合以上多个操作 @CacheConfig shares some common cache-related settings at class-level 在类级别共享缓存的相同配置 使用缓存 开启缓存注解 并使用注解 @EnableCaching 启动程序 @Cacheable({"category"}) @Override 实现类 //每一个需要缓存的数据我们都来指定要放到那个名字的缓存。[缓存的分区 (按照业务类型分)] //代表当前方法的结果需要缓存,如果缓存中有,方法不用调用。如果缓存中没有,会调用方法,最后将方法的结果放入缓存自定义缓存 SPEL 语法
指定生成的缓存使用的key -》 key属性指定 接受一个sqel 指定缓存的数据的存话时间 配置文件中设置失效时间 -》spring.cache.redis.time-to-live=360000 //毫秒 将数据保存为Json格式 @Cacheable(value = {"category"},key ="#root.method.name" ) //key ="'level1Categorys'" CacheAutoConfiguration->RedisCacheConfiguration 自动配置->RedisCacheManager->初始化缓存-> ->初始化所有的缓存-)每个缓存决定使用什么配置- ->如果redisCacheConfiguration有就用已有的,没有就用默认配置 ->想改缓存的配置,只需要给容器中放一-个RedisCacheConfiguration即可 ->就会应用到当前RedisCacheManager管理的所有缓存分区中
redis 客户端倒计时TTL 不生效 自定义配置
MyCacheConfig
//CacheProperties.class 生效 配置redisProperties 开启功能 @EnableConfigurationProperties(CacheProperties.class) @EnableCaching @Configuration public class MyCacheConfig { @Bean RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){ //改造 覆蓋原來的 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); //传入序列化器K V config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())); // GenericJackson2JsonRedisSerializer转换json序列化 config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); //装配CacheProperties 获取redist 使下面生效 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; } }