0
点赞
收藏
分享

微信扫一扫

【Java进阶营】SpringCache 缓存框架

干自闭 2022-05-01 阅读 34

目录

1、简介
2、构建项目
3、注解、表达式语法
4、自定义缓存、缓存穿透解决

简介

1、概述

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

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

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

使用Spring缓存抽象时我们需要关注以下两点;
(1)确定方法需要被缓存以及他们的缓存策略.
(2)从缓存中读取之前缓存存储的数据

2、关系图

image

二、构建项目

1、引入坐标

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

2、写配置

spring.cache.type=redis
spring.redis.host=101.34.181.131
spring.redis.port=6379

3、开启缓存功能

@EnableCaching

三、注解

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

1、@Cacheable

代表这个是可以缓存的(在 TestServerImpl)
    // 指定一个分区名字:比如用户实体,在人类分区下(也可以指定多个,逗号隔开)
    // 表示当前方法返回的结果需要缓存,如果缓存中有,则不调用当前被注解声明的方法。反之。(调式就知道了)
    @Cacheable(("Person"))
    @Override
    public List<User> getUsers() {
        // dao层数据。。。。
        List<User> userList = new ArrayList<> ();
        userList.add (new User("1","小白",18));
        userList.add (new User("2","小黑",17));
        userList.add (new User("3","小黑",17));

        return userList;
    }

2、@CacheEvict 清除缓存(失效模式)

    // 清空所有关联的数据
    // 失效模式
    //@CacheEvict(value = "Person" ,key = "'getUsers'")// 清楚一个
//    @Caching(evict = {
//            @CacheEvict(value = "Person" ,key = "'getUsers'"),
//            @CacheEvict(value = "Person" ,key = "'getUsers2'")
//    })// 清楚多个
    @CacheEvict(value = "Person",allEntries = true)// 清除整个分区下的所有key
    @Override
    public List<User> deleteList() {
        return null;
    }

3、@CachePut 更新缓存(双写模式)

    // 更新缓存,双写模式
    @CachePut(value = "Person",key = "'getUsers'")
    @Override
    public List<User> updateList() {
        // dao层数据。。。。
        List<User> userList = new ArrayList<> ( );
        userList.add (new User ("1", "小白", 18));
        return userList;
    }

4、默认行为

(1)如果缓存中有key,方法不被调用(及时db和内存的不一样),反之
(2)key默认自动生成:Person::SimpleKey []
(3)缓存中value的值,使用 jdk序列化机制,将序列化后的数据存到redis
(4)默认时间 -1 表示永不失效(不符合规范,应该有过期时间)。在此我向大家推荐一个架构学习交流圈。交流学习指导伪鑫:1253431195(里面有大量的面试题及答案)里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

5、自定义缓存生成的 key

(1)指定生成的 key名字
(2)指定过期时间
(3)将数据保存为 JSON格式

6、表达式解决 自定义key

    // 分区名 value ,key名 方法名(表达式)
    @Cacheable(value = "Person",key = "#root.method.name")

7、配置文件设置过期时间(写死的,会有雪崩问题)

 #毫秒单位
spring.cache.redis.time-to-live=360000

四、自定义配置

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching// 开启缓存
public class MyCacheConfig {

//    @Autowired
//    CacheProperties cacheProperties;

    /**
     * 自定义 Redis配置文件
     *
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig ( );
        //实例化key的序列化器对象
        RedisSerializer<String> redisSerializer = new StringRedisSerializer ( );
        //实例化value的序列化器对象
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer<> (Object.class);

        //覆盖key的序列化方式
        config = config.serializeKeysWith (RedisSerializationContext.SerializationPair.
                fromSerializer (redisSerializer));
        //覆盖value的序列化方式
        config = config.serializeValuesWith (RedisSerializationContext.SerializationPair.
                fromSerializer (jackson2JsonRedisSerializer));

         CacheProperties.Redis redisProperties = cacheProperties.getRedis ( );

         // 配置文件生效
        if (redisProperties.getTimeToLive ( ) != null) {
            Duration timeToLive = redisProperties.getTimeToLive ( );
            // 配置文件中设置的过期时间
            long seconds = timeToLive.getSeconds ( );
            config = config.entryTtl (redisProperties.getTimeToLive ( ));
        }
        if (redisProperties.getKeyPrefix ( ) != null) {
            config = config.prefixCacheNameWith (redisProperties.getKeyPrefix ( ));
        }
        if (!redisProperties.isCacheNullValues ( )) {
            config = config.disableCachingNullValues ( );
        }
        if (!redisProperties.isUseKeyPrefix ( )) {
            config = config.disableKeyPrefix ( );
        }
        return config;

    }
}

spring.cache.type=redis
spring.redis.host=101.34.181.131
spring.redis.port=6379

#毫秒单位
spring.cache.redis.time-to-live=360000
#缓存key加上前缀
spring.cache.redis.key-prefix=CACHE_
#开启前缀
spring.cache.redis.use-key-prefix=true
#是否缓存控制(防止穿透问题)
spring.cache.redis.cache-null-values=true

五、SpringCache读,写不足和原理

举报

相关推荐

0 条评论