SpringCache使用

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)

9、双写模式@CachePut,方法有返回值的有效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值