【Spring】之 Spring Cache

一、Spring Cache 简介


  • 之前我们操作 Redis 缓存的时候使用的是 Spring Boot 提供的 RedisTemplate 或者 StringRedisTemplate。这种操作需要的编码比较多一点,所以,Spring 从 3.1 开始就定义了 org.springframework.cache.Cacheorg.springframework.cache.CacheManager 接口来统一不同的缓存技术,并支持使用 JCahce(JSR-107) 注解简化我们的开发。

  • Cache 接口定义了缓存组件的规范,包含了缓存的各种操作集合;Spring 的 Cache 接口为我们提供了各种 xxxCache 的实现,比如:RedisCache、EhCacheCache、ConcurrentMapCache 等等。

  • 每次调用需要缓存功能的方法时,Spring 会检查指定参数的指定目标方法是否已经被调用过;如果有被调用过就直接从缓存中获取方法调用后的结果,如果没有就调用方法并把结果放到缓存中再返回给用户,下次调用时直接从缓存中获取。

Spring Cache 官方文档:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/integration.html#cache


二、Spring Cache 实战


1、项目整合 Spring Cache

1)、引入依赖

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

2)、添加配置

# 操作的缓存类型为 redis
spring.cache.type=redis

# spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000

# 如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true

# 是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

3)、开启缓存功能

@EnableCaching
@SpringBootApplication
public class MyApplication {
    ....
}

2、使用 Spring Cache

Spring Cache 主要使用注解的方式来完成缓存的操作,主要的注解如下:

  • @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.(在类级别共享缓存的相同配置)

1)、@Cacheable 注解

@Cacheable(value = {"category"}, key = "#root.method.name")
public CategoryEntity getCategory() {
    // get CategoryEntity
}

使用 @Cacheable 注解修饰的方法代表当前方法的结果需要缓存,如果缓存中有,方法都不用调用,如果缓存中没有,会调用方法,最后将方法的结果放入缓存。

value 属性表示缓存的分区,每一个需要缓存的数据我们都应该指定要放到哪个名字的缓存分区(缓存的分区按照业务类型区分)。这里我们指定方法返回的数据存放到 “category” 分区中。

key 属性表示缓存中存放数据的 key 的命名规则,key 的默认生成规则为:缓存的名字::SimpleKey::[] (自主生成的 key 值),这里我们使用自定义规则命名,key 属性值只支持 SpEL 表达式,"#root.method.name" 表示使用方法名作为缓存数据的 key 值。同时,如果我们在配置文件中配置了 key 值的前缀,那么将会结合前缀一起拼接成最终的缓存 key 值。

缓存的 value 值,默认使用 jdk 序列化机制,将序列化的数据存到 redis 中,并且设置过期时间 ttl 为 -1(永不过期)。想要修改过期时间可以在配置文件中设置过期时间,就如前面添加的配置。

2)、自定义缓存配置

前面使用 @Cacheable 注解时提过,缓存的 value 值为 jdk 序列化后的值,如果我们想把 value 值改为 JSON 格式的数据的话就需要进行自定义缓存配置。

自定义缓存配置很简单,就是创建我们的 Cache 配置类:

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
    
    // 引入 CacheProperties 参数使配置文件的配置生效
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {

        // 创建 Redis 缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        
        // 配置缓存 key 为 String 类型,value 为 JSon 类型
        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;
    }

}

说明如下:

  • 1、由于我们添加 Cache 的配置类,所以把 @EnableCaching 注解移到配置类中;
  • 2、一旦我们添加了自己的自定义配置类,原先在配置文件中的配置将会失效,因为源码中会读取配置文件中的配置信息;
  • 3、所以为了可以加载配置文件中的配置,我们按照源码的配置方式进行配置:首先添加 @EnableConfigurationProperties(CacheProperties.class) 注解开启配置文件读取功能,并引入 CacheProperties 对象,由于这个类对象已经交给了 Spring 容器管理,所以我们不需要使用 @Autowired 进行注入,直接作为参数引入即可。

3)、@CacheEvict 注解

@CacheEvict(value = "category", key = "#root.method.name")
public void updateCascade(CategoryEntity category) {
    // ......
}

@CacheEvict 注解对应我们说的失效模式,这个注解会中我们的缓存中删除对应的数据:

  • value 指定要删除数据所在的缓存分区;
  • key 指定要删除缓存数据的 key,其使用规则和 @Cacheable 一致

如果要删除多个 key,可以使用 @Caching 注解进行组合:

@Caching(evict = {
    @CacheEvict(value = "category",key = "'category1'"),
    @CacheEvict(value = "category",key = "'category2'")
})

注意:在 SpEL 表达式中,普通字符串需要以单引号括起来。

当然除了使用 @Caching 注解之外还可以使用 allEntries 属性来批量删除:

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

4)、@CachePut 注解

@CachePut 注解就是对应我们说的双写模式,使用 @CachePut 注解修饰的方法如果修改了数据库的数据,则会把返回值结果放到缓存中,所以 @CachePut 注解修饰的方法一定要有返回值。

3、Spring Cache 的不足之处

Spring Cache 的原理

CacheManager(RedisCacheManager) -> Cache(RedisCache) -> Cache 负责缓存的读写

在读模式下

解决缓存穿透问题可以通过设置主不存在的数据值为 null 数据,对应在配置文件中开启即可:

# 是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

对于缓存雪崩问题,还是使用加随机值和加过期时间来解决。

而对于缓存击穿问题,由于 Spring Cache 默认是无锁的,所以无法通过加锁来解决,但 @Cacheable 提供了另一个参数,syn 同步参数:

@Cacheable(value = {"category"}, key = "#root.method.name", sync = true)

设置 syn 参数为 true 之后,Spring Cache 就会以同步方式进行数据操作,相当于加了一把锁。

在写模式下

我们需要解决缓存与数据库一致性问题:

  • 加读写锁
  • 引入 Cannal 组件,Cannal 会感知到 MySQL 的更新,然后去更新 Redis
  • 读多写多的数据直接去数据库查询就可以了

总结

  • 常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache)
  • 写模式下只要缓存的数据有过期时间就足够了
  • 特殊数据使用特殊设计
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值