1.在pom中导入springCache启动器的依赖
<!-- 整合springCache缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 导入redis依赖,这里会引起堆外内存溢出,我们使用jedis-->
<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>
<!-- 导入jedis,我们使用这个-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.在配置文件中配置缓存使用的类型
# 配置缓存类型
cache:
type: redis
redis:
# 保存一个小时的存活时间
time-to-live: 3600000
# 定义k的前缀
key-prefix: CACHE_
# 是否使用k的前缀
use-key-prefix: true
cache-null-values: true
# 是否缓存null值
3.在主启动类上开启缓存功能
@EnableCaching//开启缓存功能
4.测试使用缓存:注解
@Cacheable:触发将数据保存到缓存的操作
@CacheEvict:触发将数据从缓存删除的操作
@CachePut:不影响方法执行更新缓存
@Cacheing:组合以上多个操作
@CacheConfig:在类级别共享缓存的相同配置
5.因为redis中的数据格式不是json,我们需要配置类,进行自定义配置序列化方式
@Configuration
@EnableConfigurationProperties(CacheProperties.class)//导入这个类的配置文件
public class MyCacheConfig {
/**
* 向容器中加入这个配置,就可以实现向redis中存储数据指定数据格式
* @return
*/
@Bean
RedisCacheConfiguration getRedisCacheConfiguration(CacheProperties cacheProperties){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//链式调用返回的方法
// config = config.entryTtl()
//这里分别设置k和v的序列化方式,创建一个string类型的序列化器
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;
}
}