REDIS12_Spring Cache概述、@Cacheable、@CacheEvict、@Caching、@CachePut的使用

①. Spring Cache概述

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

  • ②.Spring 从 3.1开始定义了org.springframework.cache.Cache和 org.springframework.cache.Cache Manager接口来统一不同的缓存技术,并支持使用 JCache(JSR-107)注解简化我们开发

  • ③. JSR-107 定义了5个核心接口来实现缓存操作,分别是CachingProvider, CacheManager, Cache, Entry和Expiry
    在这里插入图片描述

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

  • ⑤. SpringCache常用注解详解

注解解释
@Cacheable触发将数据保存到缓存的操作
@CacheEvict触发将数据从缓存删除的操作
@CachePut不影响方法执行更新缓存 双写模式
@Caching组合以上多个操作
@CacheConfig在类级别共享缓存的相同配置

②. Spring cache入门案列@Cacheable

  • ①. 导入pom文件,在主启动类上添加@EnableCaching
<!--引入redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--cache-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>   
@EnableCaching
@SpringBootApplication
public class testSpringCache{
    public static void main(String[] args) {
        SpringApplication.run(testSpringCache.class, args);
    }

}
//application.properties
spring.cache.type=redis
#spring.cache.cache-names=
  • ②. 业务类
 /**
  * @Cacheable
  *(代表当前方法的结果需要缓存,如果缓存中有,方法不用调用
  *如果缓存中没有,会调用方法,最后将方法的结果放入到缓存)
  *1、每一个需要缓存的数据我们都来指定要放到那个名字的缓存(缓存的分区,按照业务类型分)
  *2、默认行为
  *   (1). 如果缓存中有,方法不再调用
  *   (2). key是默认自动生成的,包含缓存名字::SimpleKey(自动生成的key值)
  *   (3). 缓存的value的值。默认使用jdk序列化机制,将序列化后的数据存到redis
  *   (4). 默认过期时间是 -1
  */
@Cacheable(value={"category"})
@Override
public List<CategoryEntity> getLevel1Category() {
    long l= System.currentTimeMillis();
    QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
    wrapper.eq("parent_cid",0);
    List<CategoryEntity> entities = baseMapper.selectList(wrapper);
    log.info("消耗时间:"+(System.currentTimeMillis()-l));
    return entities;
}
  • ③. 测试得到的结果:
  1. 如果缓存中有,方法不再调用
  2. key是默认自动生成的,包含缓存名字::SimpleKey(自动生成的key值)
  3. 缓存的value的值。默认使用jdk序列化机制,将序列化后的数据存到redis
  4. 默认过期时间是 -1
    在这里插入图片描述在这里插入图片描述
  • ④. 指定自己的key,并设置过期时间
//application.properties
spring.cache.type=redis
#spring.cache.cache-names=
#设置存活时间,ms为单位
spring.cache.redis.time-to-live=3600000
/**
自定义
(1). 指定生成缓存的key key属性指定,接收一个spl表达式
详细文档:https://docs.spring.io/spring-framework/docs/5.2.16.RELEASE/spring-framework-reference/integration.html#cache-spel-context
(2). 指定缓存的数据存活时间(在配置文件中修改了ttl)
*/

@Cacheable(value={"category"},key = "'Level1Categorys'")
@Override
public List<CategoryEntity> getLevel1Category() {
    long l= System.currentTimeMillis();
    QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
    wrapper.eq("parent_cid",0);
    List<CategoryEntity> entities = baseMapper.selectList(wrapper);
    log.info("消耗时间:"+(System.currentTimeMillis()-l));
    return entities;
}

在这里插入图片描述

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

在这里插入图片描述

③. JSON格式转换、空值缓存

  • ①. 上面的配置中,可以指定名称、并且过期时间已经配置了,关于JSON格式还没有解决

  • ②. SpringCache的配置原理

*   CacheAutoConfiguration导入了RedisCacheConfiguration,RedisCacheConfiguration自动配置了缓存管理器RedisCacheManager
*   RedisCacheManager->初始化所有的缓存->每个缓存决定使用什么配置->按照配置文件中配置的名字进行初始化,决定用哪种配置(redisCacheConfiguration)
*   ->如果redisCacheConfiguration有就用自己有的,没有就用默认配置
*   ->想改配置,只需要给容器放一个RedisCacheConfiguration
*   ->就会应用到当前RedisCacheManager管理的所有缓存中(缓存分区)
  • ③. 新建配置类,进行JSON格式转换
    注意:要让配置文件中的配置生效,需要加上@EnableConfigurationProperties(CacheProperties.class)
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
@Configuration
public class MyCacheConfig {
    /**
     * 要让配置文件中的配置生效,需要加上@EnableConfigurationProperties(CacheProperties.class)
     * @param cacheProperties
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //值变成JSON格式
        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;
    }
}

在这里插入图片描述

  • ④. 配置前缀、空值缓存等功能
//application.properties
spring.cache.type=redis
#spring.cache.cache-names=
#设置存活时间,ms为单位
spring.cache.redis.time-to-live=3600000
#如果指定了前缀,就使用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#CACHE_getLevel1Category
spring.cache.redis.key-prefix=CACHE_
#默认是使用前缀的
#如果开启了这个,那么缓存的key=getLevel1Category,没有CACHE
spring.cache.redis.use-key-prefix=false
#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

④. @CacheEvict、@Caching、@CachePut的使用

  • ①. @CacheEvict:触发将数据从缓存删除的操作(相当于失效模式)
    @CacheEvict(value = "category",key = "'getLevel1Category'")
    @Transactional
    @Override
    public void updateCasCade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
  • ②. @Caching:组合以上多个操作
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Category'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })
    //删除category分区中所有的数据
    //@CacheEvict(value = "category",allEntries = true)//失效模式
    @Transactional
    @Override
    public void updateCasCade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
   /**
     * @Cacheable
     *(代表当前方法的结果需要缓存,如果缓存中有,方法不用调用
     *如果缓存中没有,会调用方法,最后将方法的结果放入到缓存)
     *1、每一个需要缓存的数据我们都来指定要放到那个名字的缓存(缓存的分区,按照业务类型分)
     *2、默认行为
     *   (1). 如果缓存中有,方法不再调用
     *   (2). key是默认自动生成的,包含缓存名字::SimpleKey(自动生成的key值)
     *   (3). 缓存的value的值。默认使用jdk序列化机制,将序列化后的数据存到redis
     *   (4). 默认过期时间是 -1
     *3、自定义
     *   (1). 指定生成的缓存使用的key
     *   (2). 指定缓存的数据的存活时间
     *   (3). 将数据保存为json格式
     */
    @Cacheable(value = {"category"},key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        long l= System.currentTimeMillis();
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid",0);
        List<CategoryEntity> entities = baseMapper.selectList(wrapper);
        log.info("消耗时间:"+(System.currentTimeMillis()-l));
        return entities;
    }

    /**
     *渲染二级三级分类数据
     * @return
     */
    @Cacheable(value = "category",key ="#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        log.info("二三级分类查询了数据库!!!!");
        //1.查出所有的一级分类
        //List<CategoryEntity> level1Category = this.getLevel1Category();
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        List<CategoryEntity> level1Category = getParent_cid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //List<Catelog2Vo>
            //1.每一个的一级分类,查到这个一级分类的二级分类(查询二级分类)
            List<CategoryEntity> l2 = getParent_cid(selectList, v.getCatId());
            //2.封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (l2 != null) {
                catelog2Vos = l2.stream().map((item2) -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
                    //1.找当前二级分类的三级分类封装成VO(查询三级分类)
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, item2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map((l3) -> {
                            //2. 封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(item2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • ③. @CachePut:不影响方法执行更新缓存(双写模式) 需要有返回值

⑤. SpringCache原理与不足

  • ①. 读模式
  1. 缓存穿透:查询一个null数据。解决方案:缓存空数据,可通过spring.cache.redis.cache-null-values=true
  2. 缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;
  3. 使用sync = true来解决击穿问题
  4. 缓存雪崩:大量的key同时过期。解决:加随机时间。
// 解决缓存击穿加锁 
@Cacheable(value={"category"},key = "#root.method.name",sync = true)
  • ②. 写模式(缓存与数据库一致)
  1. 读写加锁。
  2. 引入Canal,感知到MySQL的更新去更新Redis
  3. 读多写多,直接去数据库查询就行
  • ③. 总结
  1. 常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):
  2. 写模式(只要缓存的数据有过期时间就足够了)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

所得皆惊喜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值