RedisCache存入redis的数据key为何name和id的分隔符是两个冒号::

Redis Cache缓存数据生成的key是由两部分组成,cacheNames和+d或者自定义生成方案,如果采用cacheNames+id方案则会在中间添加两个冒号::,这样使用工具查看的时候感觉怪怪的,今天我们就探讨下具体生成原因。

一、CacheKeyPrefix钩子回调接口
java 复制代码
@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;
	}
}

回调函数定义了simple()和prefixed()两个方法将定义的name和双冒号拼接

二、具体使用代码RedisCacheConfiguration#prefixCacheNameWith
java 复制代码
	/**
	 * 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));
	}

注解标记拼接方案是:prefix + cache name + "::" + cache entry key

三、配置类RedisCacheConfiguration#createConfiguration调用上述方法
java 复制代码
	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

相关推荐
草履虫建模5 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
A-刘晨阳5 小时前
【Linux】Redis 6.2.6 的二进制部署【适用于多版本】
linux·运维·redis
程序猿ZhangSir7 小时前
Redis 缓存进阶篇,缓存真实数据和缓存文件指针最佳实现?如何选择?
数据库·redis·缓存
段帅龙呀15 小时前
Redis构建缓存服务器
服务器·redis·缓存
用户8324951417321 天前
Spring Boot 实现 Redis 多数据库切换(多数据源配置)
redis
傲祥Ax1 天前
Redis总结
数据库·redis·redis重点总结
夜斗小神社1 天前
【黑马点评】(二)缓存
缓存
都叫我大帅哥1 天前
Redis AOF持久化深度解析:命令日志的终极生存指南
redis
都叫我大帅哥1 天前
Redis RDB持久化深度解析:内存快照的魔法与陷阱
redis
Hello.Reader2 天前
Redis 延迟监控深度指南
数据库·redis·缓存