Loading

SpringCache

在业务中要使用缓存就要考虑缓存的两种用法模式,一种是读模式:遵循先从缓存中读取数据,缓存中没有再读取数据库,一种是写模式:双写方式、失效方式。这样每一套代码都需要这样一套代码,比较麻烦,有一个简单的方式来整合使用缓存。

简介

  • Spring 从 3.1 开始定义了 org.springframework.cache.Cache 和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术;并支持使用 JCache(JSR-107)注解简化我们开发;
  • Cache 接口为缓存的组件规范定义,包含缓存的各种操作集合;Cache 接 口 下 Spring 提 供 了 各 种 xxxCache 的 实 现 ; 如 RedisCache , EhCacheCache , ConcurrentMapCache 等;
  • 每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已 经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓 存结果后返回给用户。下次调用直接从缓存中获取。

使用 Spring 缓存抽象时我们需要关注以下两点;

1、确定方法需要被缓存以及他们的缓存策略

2、从缓存中读取之前缓存存储的数据

整合SpringCache简化开发

引入依赖

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

添加配置

自动配置了:
● CacheAutoConfiguration 会导入 RedisCacheConfiguration;
● 会自动装配缓存管理器 RedisCacheManager;
手动配置:
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

然后在MyredisConfig加上@EnableCaching注解启用缓存

常用注解

  • @Cacheable :触发将数据保存到缓存的操作;

  • @CacheEvict : 触发将数据从缓存删除的操作;

  • @CachePut :不影响方法执行更新缓存;

  • @Cacheing:组合以上多个操作;

  • @CacheConfig:在类级别共享缓存的相同配置;

整合@Cacheable业务实现

配置所在的缓存分区,在读缓存的时候如果有数据就不用调用方法

    /*
    * 查询商品一级分类
    * */
    @Cacheable("{Category}")
    @Override
    public   List<CategoryEntity>  selectLevel1Category() {
        QueryWrapper<CategoryEntity> queryWrapper=new QueryWrapper<CategoryEntity>();
        queryWrapper.eq("parent_cid",0);
        List<CategoryEntity> categoryEntities = baseMapper.selectList(queryWrapper);
        return  categoryEntities;
    }

image-20211006220841270

自定义配置

自定义操作:key的生成

  1. 指定生成缓存的key:key属性指定,接收一个 SpEl
  2. 指定缓存的数据的存活时间:配置文档中修改存活时间 ttl
  3. 将数据保存为json格式: 自定义配置类 MyCacheManager
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {

    /**
     * 配置文件的配置没有用上
     * 1. 原来和配置文件绑定的配置类为:@ConfigurationProperties(prefix = "spring.cache")
     *                                public class CacheProperties
     * <p>
     * 2. 要让他生效,要加上 @EnableConfigurationProperties(CacheProperties.class)
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        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;
    }
}

从缓存中写数据

写数据对应两种模式:失效方式、双写方式分别是SpringCache中的

  • @CacheEvict : 触发将数据从缓存删除的操作;

    只要数据被更改了,就会把缓存删除,直到下一次查询进来
    1.有时候更新需要清空多个方法的缓存,不能在一个方法上加上多个`@CacheEvict`注解,就需要用到`@Cacheing`
      @Caching(evict = {
                @CacheEvict(value = "category",key = "'selectLevel1Category'")
        })
    
    2.删除某个分区下的所有数据
    @CacheEvict(value = "category",allEntries = true)
    
  • @CachePut :不影响方法执行更新缓存;

  • @Cacheing:组合以上多个操作

Spring-Cache的不足之处

读模式

  • 缓存穿透:查询一个null数据。解决方案:缓存空数据
  • 缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
  • 缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间

2)、写模式:(缓存与数据库一致)

  • 读写加锁。
  • 引入Canal,感知到MySQL的更新去更新Redis
  • 读多写多,直接去数据库查询就行

总结

常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了)

特殊数据:特殊设计

posted @ 2021-10-12 16:52  炒焖煎糖板栗  阅读(122)  评论(0编辑  收藏  举报