• SpringCache的简介和使用


    1、简介

    Spring 从 3.1 开始定义了 org.springframework.cache.Cache 和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术;

    并支持使用 JCache(JSR-107)注解简化我们开发

    Cache 接口为缓存的组件规范定义,包含缓存的各种操作集合; Cache 接 口 下 Spring 提 供 了 各 种 xxxCache 的 实 现 ; 如 RedisCache ,

    EhCacheCache , ConcurrentMapCache 等;

    每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法

    调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取

    2、整合SpringCache简化缓存开发

    1)引入依赖

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

    2)添加配置

    spring.cache.type=redis

    3)测试使用缓存

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

    ①、主启动类上添加 @EnableCache注解,开启缓存功能

    ②、只需要使用注解就可以完成缓存操作

    当方法的结果需要缓存到数据库,在方法上加上 @CacheEnable注解

    /*
    1、每一个需要缓存的数据,我们都要来指定要放到哪个名字的缓存。【相当于缓存的分区(按照业务类型来进行分区)】
    2、代表当前方法的结果需要缓存,如果缓存中有,方法不调用;如果缓存中没有,会调用方法,并将方法返回的结果放入缓存
    3、默认行为
        1)如果缓存中有,方法不能调用
        2)key值默认生成,缓存的名字::simplekey []
        3)缓存的value的值默认使用jdk序列化机制,将序列化后的数据存储到redis
        4)默认缓存过期时间是-1(用户过期)
    
        自定义:
        1)指定缓存生成的key: 指定key-> spel表达式
        2)指定缓存的数据的过期时间:配置文件指定
        3)将数据保存为json格式:
    
    */
    @Cacheable("category")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys方法执行......");
        List<CategoryEntity> categoryEntities = this.baseMapper
            .selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", "0"));
        return categoryEntities;
    }

    第一次访问该方法时,需要访问数据库;第二次访问该方法时,则直接从缓存中获取

    ③、以自定义的方式设置key的名称和过期时间

    @Cacheable(value = {"category"},key="'level1Categorys'")

    配置文件中添加

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

    0

    ④、更多自定义配置

    配置key,value的序列化机制:

    /**
     * @author houChen
     * @date 2021/11/4 6:59
     * @Description:
     *
     * 缓存配置类
     *    @ConfigurationProperties(prefix = "spring.cache") : 只是使类中的属性和配置文件绑定,并不能注入到容器中
     *
     */
    @EnableConfigurationProperties(CacheProperties.class)    //@EnableConfigurationProperties注解 可以使CacheProperties类注入到容器中
    @Configuration
    @EnableCaching
    public class MyCacheConfig {
    
        @Bean
        RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
            config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
            config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    
            CacheProperties.Redis redisCacheProperties = cacheProperties.getRedis();
            if(redisCacheProperties.getTimeToLive()!=null){
                config = config.entryTtl(redisCacheProperties.getTimeToLive());
            }
            return config;
        }
    }

    ⑤、使用@CacheEvict (去除缓存)

    指定删除某个分区下的所有数据

    @CacheEvict(value="category",allEntries=true)
    
    

    约定:

    同一个类型的数据,可以缓存在相同名称的分区中!

    3、SpringCache的原理和不足

    1)读模式

    缓存穿透:查询一个null数据。解决:缓存空数据:cache-null-values=true

    缓存击穿:大量并发请求进来同时查询一个正好过期的数据。 解决: 加锁

    缓存雪崩:大量的key同时过期 解决:加随机时间

    2)写模式 (如何保证缓存和数据库一致性)

    1)加锁模式

    2)引入canal

    3)读多写多,直接去数据库查询

  • 相关阅读:
    CSAPP DataLab
    《计算机网络自顶向下》第二章应用层,笔记总结
    计算机网络自顶向下第二章套接字编程作业
    第二章---信息的表示与处理
    python界面使用gbk编码
    python修改获取xlsx数据
    刚安装了ftp之后无法使用root访问,服务器发回了不可路由的地址。使用服务器地址代替。
    ssh_exchange_identification: read: Connection reset
    <七>对于之前的一些遗漏的地方的补充
    (六)单例模式与多线程时的安全问题以及解决办法
  • 原文地址:https://www.cnblogs.com/houchen/p/15617466.html
Copyright © 2020-2023  润新知