Spring Cache @Cacheable、@CacheEvict、@CachePut、@Cacheing 使用

前言

Java学习路线个人总结-博客
❤欢迎点赞👍收藏⭐留言 📝分享给需要的小伙伴

引入依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

添加配置

自动配置

  • CacheAutoConfiguration 会导入 RedisCacheConfiguration;
  • 会自动装配缓存管理器 RedisCacheManager;
  • 启动类添加 @EnableCaching
  • 方法添加Cacheable(value={“category”})

手动配置

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {

    /**
     * 配置文件的配置没有用上
     * 1. 原来和配置文件绑定的配置类为:@ConfigurationProperties(prefix = "spring.cache")
     * public class CacheProperties
     * <p>
     * 2. 要让他生效,要加上直接绑定类CacheProperties @EnableConfigurationProperties(CacheProperties.class)
     *
     * 1、第一种使用方式
     * @Autowired
     * CacheProperties cacheProperties
     * 2、因为配置都在容器中了,可以直接作为参数传过来
     *   public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties)
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        //JSON序列化数据 key value
        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());
        }
        // 指定key前缀
        // 2.3之前使用prefixKeysWith 之后使用 prefixCacheNameWith or computePrefixWith
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        //是否缓存null
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        //是否使用键前缀
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }

}

application.yml


spring:
  #cache配置
  cache:
    type: redis
    redis:
      #毫秒为单位,存活时间
      time-to-live: 3600000
      #指定redis KEY前缀 如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀,一般情况下不进行指定前缀还是用分区名称作为前缀可以组合或批量操作
      key-prefix: CACHE_
      #是否开启缓存前缀
      use-key-prefix: true
      #是否缓存空值,可以防止缓存穿透
      cache-null-values: true

常用注解

  • @Cacheable : 触发将数据保存到缓存的操作;
  • @CacheEvict : 触发将数据从缓存删除的操作;
  • @CachePut : 不影响方法执行更新缓存;
  • @Cacheing: 组合以上多个操作;
  • @CacheConfig: 在类级别共享缓存的相同配置;

缓存Key指定

属性名称描述示例
methodName当前方法名#root.methodName
method当前方法#root.method.name
target当前被调用的对象#root.target
targetClass当前被调用的对象的class#root.targetClass
args当前方法参数组成的数组#root.args[0]
caches当前被调用的方法使用的Cache#root.caches[0].name

业务使用

添加缓存

value:缓存分区
key: 缓存Key

@Cacheable(value = {"category"}, key = "#root.method.name")
@Override
public Map<String,String> test() {
   //查询数据
    return null;
}

缓存失效

在修改数据的时候,修改完成会将缓存的数据清空
value:指定分区
key: 指定Key

@CacheEvict(value = {"category"}, key = "'test'") 
public void updateTest(Test test) {
    //更新数据
}

批量操作

@CacheEvict:组合多个操作;

//同时清除多个缓存操作
@Caching(evict = {
            @CacheEvict(value = {"category"}, key = "'test'"),
            @CacheEvict(value = {"category"}, key = "'test1'")
    })

//指定删除某个分区一下的所有数据
@CacheEvict(value = {"category"}, allEntries = true)

修改数据

执行方法体 - 将结果缓存起来;

@CacheEvict(value = {"test"}, key = "#test.id")
public void updateTest(Test test) {
    //更新数据
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冒险的梦想家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值