简介
基本概念
整合
引入依赖
````````<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>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
配置
配置文件
spring.cache.type=redis
原理
测试使用
//每一个需要缓存的数据我们都要指定放到哪个名字缓存【缓存分区类型(按照业务类型分)】
@Cacheable{"缓存区的名字,“缓存区的名字"} //直接在方法上面使用就可以了
//如果当前缓存的结果需要缓存,如果缓存中有,方法不调用,如果缓存中没有,会调用方法,最后将方法的结果放入缓存
默认行为
1、如果缓存中有,方法不调用
2、key默认自动生成,缓存名字::simpleKey【】(自动生成的key)
3、缓存的value的值,默认使用jdk序列化机制,将序列化以后的数据存到redis
4、默认过期时间是永不过期 ttl -1
自定义
- 指定生成缓存使用的key 注解Cacheable 的key属性 接受一个spel表达式 spel语法参考百度,但是如果不想使用,就直接 “’’”
- 指定缓存数据的存活时间 在配置文件中修改ttl 单位是毫秒
- 将数据存为json格式
知识点
要想让不在容器中的类生效,可以使用
@EnableConfigurationProperties(CacheProperties.class)
配置文件
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {
@Bean
public org.springframework.data.redis.cache.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;
}
}
失效模式
同时进行多种缓存操作
删除某个分区下的所有数据,存储同一类型的数据,都可以指定成同一个分区,分区名就是缓存的前缀
原理和不足
默认是没有锁
在Cacheing注解里面加入这个就可以加入锁
总结:
常规数据(读多写少,即时性不高的数据,一致性要求不高的,完全可以采用)
写模式,只要有过期时间就足够了
认是没有锁
[外链图片转存中…(img-ZznTooPe-1615959669120)]
在Cacheing注解里面加入这个就可以加入锁
总结:
常规数据(读多写少,即时性不高的数据,一致性要求不高的,完全可以采用)
写模式,只要有过期时间就足够了