一、CacheKeyPrefix钩子回调接口
@FunctionalInterface
public interface CacheKeyPrefix {
String SEPARATOR = "::";
String compute(String cacheName);
static CacheKeyPrefix simple() {
return name -> name + SEPARATOR;
}
static CacheKeyPrefix prefixed(String prefix) {
Assert.notNull(prefix, "Prefix must not be null");
return name -> prefix + name + SEPARATOR;
}
}
二、具体使用代码RedisCacheConfiguration#prefixCacheNameWith
/**
* Prefix the {@link RedisCache#getName() cache name} with the given value. <br />
* The generated cache key will be: {@code prefix + cache name + "::" + cache entry key}.
*
* @param prefix the prefix to prepend to the cache name.
* @return new {@link RedisCacheConfiguration}.
* @see #computePrefixWith(CacheKeyPrefix)
* @see CacheKeyPrefix#prefixed(String)
* @since 2.3
*/
public RedisCacheConfiguration prefixCacheNameWith(String prefix) {
return computePrefixWith(CacheKeyPrefix.prefixed(prefix));
}
三、配置类RedisCacheConfiguration#createConfiguration调用上述方法
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();
config = config
.serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
// 配置cacheName组合方案
config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
开源SDK:https://github.com/mingyang66/spring-parent