Spring Boot
支持对 Spring Cache
的开箱即用,其中包括 Redis Cache
,本文结合部分代码示例 Spring Boot Redis Cache
的相关配置,比如 序列化
@ConfigurationProperties(prefix = "spring.cache")
public class CacheProperties {
// 缓存类型
private CacheType type;
private final Redis redis = new Redis();
public static class Redis {
// 过期时间,默认永久有效
private Duration timeToLive;
// 允许缓存空值
private boolean cacheNullValues = true;
// 缓存 key 前缀
private String keyPrefix;
// 默认使用前缀
private boolean useKeyPrefix = true;
// 缓存统计?
private boolean enableStatistics;
// ...
}
// ...
}
spring.cache.xxx
配置 Spring Cache
spring.cache.type = redis
即是用 redis
缓存,同理还包括:generic
jCache
等redis
配置 过期时间
、key前缀
@Bean
RedisCacheManager cacheManager(CacheProperties cacheProperties,
// CacheManager 后处理
CacheManagerCustomizers cacheManagerCustomizers,
// RedisCacheConfiguration 自定义
ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
// RedisCacheManagerBuilder 后处理
ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {
// ...
}
CacheConfigurations
),比如 RedisCacheConfiguration
CacheManager
,比如 RedisCacheManager
CacheManagerCustomizer
类后处理 CacheManager
,很常规的模式了RedisCacheConfiguration
来实现对 RedisCacheManager
的控制RedisCacheManagerBuilderCustomizer
类后处理 RedisCacheManagerBuilder
,进而后处理默认的 RedisCacheManager
private org.springframework.data.redis.cache.RedisCacheConfiguration createConfiguration(
CacheProperties cacheProperties, ClassLoader classLoader) {
Redis redisProperties = cacheProperties.getRedis();
org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
.defaultCacheConfig();
// 默认 java 序列化
config = config.serializeValuesWith(
SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
// 默认基于 CacheProperties#redis 属性配置
if (redisProperties.getTimeToLive() != null) {
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;
}
如果上默认的 redis cache
配置:
JdkSerializationRedisSerializer
过期时间
等都基于 CacheProperties#redis
配置 @Bean
public RedisCacheManagerBuilderCustomizer serializeCustomize() {
return builder -> builder.cacheDefaults(
RedisCacheConfiguration.defaultCacheConfig()
// 指定值序列器为 json(GenericJackson2JsonRedisSerializer)
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
RedisSerializer.json()
))
// 指定缓存过期时间
.entryTtl(Duration.ofHours(1L))
);
}
如上,可以自定义 RedisCacheManagerBuilderCustomizer
:
json
(GenericJackson2JsonRedisSerializer
)ttl
(超时时间)Spring Boot
对 Cache
的支持