• 谷粒商城 高级篇 (十一) --------- Spring Cache



    一、简介

    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、从缓存中读取之前缓存存储的数据

    基础概念

    在这里插入图片描述

    二、注解

    注解说明
    Cache缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等
    CacheManager缓存管理器,管理各种缓存(Cache)组件
    @Cacheable主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
    @CacheEvict清空缓存
    @CachePut保证方法被调用,又希望结果被缓存。
    @EnableCaching开启基于注解的缓存
    keyGenerator缓存数据时key生成策略
    serialize缓存数据时value序列化策略

    @Cacheable / @CachePut / @CacheEvict 主要的参数

    参数说明示例
    value缓存的名称, 在 spring 配置文件中定义, 必须指定至少一个例如:@Cacheable(value=“mycache” 或 @Cacheable(value=“cache1”, “cache2”)
    key缓存的key,可以为空,如果指定,按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@Caheable(value=“testcache”, key=“#username”)
    allEntries(@CacheEvict)是否清空所有缓存内容,缺省为false,如果指定为 true,则方法调用后将立即清空所有缓存例如:@CachEvict(value=“test”, allEntries=true)
    beforeInvocation(@CacheEvict)是否在方法执行前就清空,缺省为false,如果指定为true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存例如: @CacheEvict(value=“testcache”, beforeInvocation=true)
    unless(@CachePut、@Cacheable)用于否决缓存的,不像 condition,该表达式只在方法执行之后判断,此时可以拿到返回值 result 进行判断。条件为 true 不会缓存,false才缓存例如:@Cacheable(vlaue=“testcache”, unless=“#result==null”)

    三、SpEL 语法

    在这里插入图片描述

    四、使用

    1. 引入依赖

    <dependency>
    	<groupId>org.springframework.bootgroupId>
    	<artifactId>spring-boot-starter-cacheartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    2. 写配置

    A、自动配置了哪些 ?

    CacheAuroConfiguration会导入 RedisCacheConfiguration;
    自动配好了缓存管理器RedisCacheManager

    B、配置使用redis作为缓存

    spring.cache.type=redis
    
    • 1

    C、也可以自定义配置,因为默认的使用 JDK 的序列化机制,我们想用 JSON 序列化机制

    package com.fancy.gulimall.product.config;
    
    import org.springframework.boot.autoconfigure.cache.CacheProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializationContext;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    @EnableCaching
    @EnableConfigurationProperties(CacheProperties.class)
    public class MyCacheConfig {
        // @Autowired
        // public CacheProperties cacheProperties;
    
        /**
         * 配置文件的配置没有用上
         * @return
         */
        @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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    3. 开启缓存注解功能

    在这里插入图片描述

    /**
    * 每一个需要缓存的数据我们都来指定要放到那个名字的缓存。【缓存的分区(按照业务类型分)】
    * 代表当前方法的结果需要缓存,如果缓存中有,方法都不用调用,如果缓存中没有,会调用方法。最后将方法的结果放入缓存
    * 默认行为
    *      如果缓存中有,方法不再调用
    *      key是默认生成的:缓存的名字::SimpleKey::[](自动生成key值)
    *      缓存的value值,默认使用jdk序列化机制,将序列化的数据存到redis中
    *      默认时间是 -1:
    *
    *   自定义操作:key的生成
    *      指定生成缓存的key:key属性指定,接收一个Spel
    *      指定缓存的数据的存活时间:配置文档中修改存活时间
    *      将数据保存为json格式
    *
    *
    * 4、Spring-Cache的不足之处:
    *  1)、读模式
    *      缓存穿透:查询一个null数据。解决方案:缓存空数据
    *      缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
    *      缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间
    *  2)、写模式:(缓存与数据库一致)
    *      1)、读写加锁。
    *      2)、引入Canal,感知到MySQL的更新去更新Redis
    *      3)、读多写多,直接去数据库查询就行
    *
    *  总结:
    *      常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了)
    *      特殊数据:特殊设计
    *
    *  原理:
    *      CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写
    * @return
    */
    @Cacheable(value={"category"}, key="#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys........");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间:"+ (System.currentTimeMillis() - l));
        return categoryEntities;
    }
    
    /**
    * 级联更新所有关联的数据
    *
    * @CacheEvict:失效模式
    * @CachePut:双写模式,需要有返回值
    * 1、同时进行多种缓存操作:@Caching
    * 2、指定删除某个分区下的所有数据 @CacheEvict(value = "category",allEntries = true)
    * 3、存储同一类型的数据,都可以指定为同一分区
    * @param category
    */
    // @Caching(evict = {
    //         @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
    //         @CacheEvict(value = "category",key = "'getCatalogJson'")
    // })
    @CacheEvict(value = "category",allEntries = true)       //删除某个分区下的所有数据
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(CategoryEntity category) {
    
       RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");
       //创建写锁
       RLock rLock = readWriteLock.writeLock();
    
       try {
           rLock.lock();
           this.baseMapper.updateById(category);
           categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           rLock.unlock();
       }
    
       //同时修改缓存中的数据
       //删除缓存,等待下一次主动查询进行更新
    }
    
    
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");
    
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
    
        //1、查出所有分类
        //1、1)查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
    
        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
    
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());
    
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
    
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
    
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }
    
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
    
            return catelog2Vos;
        }));
    
        return parentCid;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127

    五、缓存失效问题

    缓存穿透

    查询一个 null 数据。解决方案:缓存空数据

    SpringCache 中解决方案:

    在这里插入图片描述

    缓存击穿:

    大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ?
    默认是无加锁的。使用 sync = true来解决击穿问题。

    SpringCache 中解决方案:

    在这里插入图片描述

    缓存雪崩:

    大量的key同时过期。解决:加随机时间。加上过期时间

    SpringCache 中解决方案:
    在这里插入图片描述

  • 相关阅读:
    【Java分享客栈】SpringBoot线程池参数搜一堆资料还是不会配,我花一天测试换你此生明白。
    跨界协作:借助gRPC实现Python数据分析能力的共享
    需求管理手册-对交付物的要求(12)
    虹科分享 | 为工业机器人解绑,IO-Link wireless无线通讯技术可实现更加轻量灵活的机器人协作
    C语言函数复习全解析:参数、无参、嵌套与递归
    ELTEK电源维修SMPS5000SIL整流器模块故障分析及特点
    ssl 层在握手阶段报错 mbedtls_ssl_handshake returned -0xffff8880
    shiro组件漏洞分析(二)
    Mybatis入门
    MySQL事务死锁问题排查
  • 原文地址:https://blog.csdn.net/m0_51111980/article/details/126855480