• SpringCache-缓存技术


    🧑‍🎓 个人主页:花棉袄

    📖 本章内容:【SpringCache-缓存技术
    ✍🏻 版权: 本文由【花棉袄】原创💝在CSDN首发💝需要转载请联系博主

    在这里插入图片描述

    🌳 SpringCache-缓存技术🌳

    📢💨如果文章对你有帮助【关注👍点赞❤️收藏⭐】

    🍖SpringCache

    1️⃣SpringCach简介

    • spring从3.1开始定义了Cache、CacheManager接口来统一不同的缓存技术
    • 并支持使用JCache(JSR-107)注解简化我们的开发
    • Cache接口的实现包括RedisCache、EhCacheCache、ConcurrentMapCache等
    • 每次调用需要缓存功能的方法时,spring会检查检查指定参数的指定的目标方法
    • 是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就
    • 调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取

    在这里插入图片描述

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

    • 1.确定方法需要缓存以及他们的缓存策略
    • 2.从缓存中读取之前缓存存储的数据

    2️⃣SpringCach配置

    • 引入依赖
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-cacheartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • application.properties
    #指定缓存类型为redis
    spring.cache.type=redis
    # 指定redis中的过期时间为1h
    spring.cache.redis.time-to-live=1000
    
    • 1
    • 2
    • 3
    • 4
    • 指定缓存类型并在主配置类上加上注解:@EnableCaching
    @EnableCaching
    @SpringBootApplication
    public class Jrs303Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Jrs303Application.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 默认使用jdk进行序列化(可读性差),默认ttl为-1永不过期,自定义序列化方式需要编写配置类

    3️⃣将数据保存成JSON格式

    • 配置类:MyCacheConfig
    @EnableConfigurationProperties(CacheProperties.class)
    @Configuration
    public class MyCacheConfig {
        @Bean
        public RedisCacheConfiguration redisCacheConfiguration( CacheProperties cacheProperties) {
            
            CacheProperties.Redis redisProperties = cacheProperties.getRedis();
            org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
                .defaultCacheConfig();
            //指定缓存序列化方式为json
            config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
            //设置配置文件中的各项配置,如过期时间
            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

    4️⃣常用注解

    @Cacheable
    @Cacheble注解表示这个方法有了缓存的功能,方法的返回值会被缓存下来,下一次调用该方法前,会去检查是否缓存中已经有值,如果有就直接返回,不调用方法。如果没有,就调用方法,然后把结果缓存起来。这个注解一般用在查询方法上。
    
    @CachePut
    加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用。它通常用在新增方法上。
    
    @CacheEvict
    使用了CacheEvict注解的方法,会清空指定缓存。一般用在更新或者删除的方法上。
    
    @Caching
    Java注解的机制决定了,一个方法上只能有一个相同的注解生效。那有时候可能一个方法会操作多个缓存(这个在删除缓存操作中比较常见,在添加操作中不太常见)。
    
    Spring Cache当然也考虑到了这种情况,@Caching注解就是用来解决这类情况的,大家一看它的源码就明白了。
    
    public @interface Caching {
        Cacheable[] cacheable() default {};
        CachePut[] put() default {};
        CacheEvict[] evict() default {};
    }
    @CacheConfig
    前面提到的四个注解,都是Spring Cache常用的注解。每个注解都有很多可以配置的属性,这个我们在下一节再详细解释。但这几个注解通常都是作用在方法上的,而有些配置可能又是一个类通用的,这种情况就可以使用@CacheConfig了,它是一个类级别的注解,可以在类级别上配置cacheNames、keyGenerator、cacheManager、cacheResolver等。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • #root.method.name获取方法名
       @Cacheable(value = {"corgory"}, key = "#root.method.name")
        @Override
        public List<CategoryEntity> getCategoryOne() {
            System.out.println("category");
            QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_cid", 0);
            List<CategoryEntity> entityList = baseMapper.selectList(queryWrapper);
            return entityList;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在这里插入图片描述

        //@Caching(evict = {
        //        @CacheEvict(value = "category", key = "'getCategoryOne'"),
        //       @CacheEvict(value = "category", key = "'getCatalogJson'")
        //})
        @CacheEvict(value = "category", allEntries = true)
        @Transactional
        @Override
        public void updateCategory(CategoryEntity category)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
        @Cacheable(value = {"category"}, key = "#root.method.name")
        @Override
        public List<CategoryEntity> getCategoryOne()
    
    • 1
    • 2
    • 3
        @Cacheable(value = "category", key = "#root.method.name")
        @Override
        public Map<String, List<Catelog2Vo>> getCatalogJson()
    
    • 1
    • 2
    • 3

    5️⃣解决击穿问题

    # 如果制定了前缀就是用指定的,如果没有指定前缀就使用缓存名字作为前缀
    spring.cache.redis.use-key-prefix=true
    # 解决缓存穿透
    spring.cache.redis.cache-null-values=true
    
    • 1
    • 2
    • 3
    • 4
    • 使用sync = true来解决击穿问题

    🥙SpringCache原理与不足

    1️⃣读模式

    缓存穿透:查询一个null数据。解决方案:缓存空数据,可通过spring.cache.redis.cache-null-values=true
    
    缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
    
    缓存雪崩:大量的key同时过期。解决:加随机时间,加过期时间。spring.cache.redis.time-to-live=360000000
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2️⃣写模式

    • 写模式:(缓存与数据库一致)
    读写加锁
    引入Canal,感知到MySQL的更新去更新Redis
    读多写多,直接去数据库查询就行
    
    • 1
    • 2
    • 3

    3️⃣模式总结

    常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache)
    
    写模式(只要缓存的数据有过期时间就足够了)
    
    特殊数据:特殊设计
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    性能分析方法-《性能之巅》笔记
    div+css布局实现个人网页设计(HTML期末作业)
    Swoole系列(3) - 服务端 (异步风格)
    震惊,99.9% 的同学没有真正理解字符串的不可变性
    某安全设备frp流量告警分析
    RPC和HTTP调用的区别
    论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
    第二部分:CSS3
    史上最详细vue的入门基础
    华为机试真题 C++ 实现【租车骑绿岛】【2022.11 Q4新题】
  • 原文地址:https://blog.csdn.net/m0_46914264/article/details/126277605