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

相关推荐
敖云岚1 小时前
【Redis】分布式锁的介绍与演进之路
数据库·redis·分布式
让我上个超影吧3 小时前
黑马点评【基于redis实现共享session登录】
java·redis
懒羊羊大王呀6 小时前
Ubuntu20.04中 Redis 的安装和配置
linux·redis
John Song8 小时前
Redis 集群批量删除key报错 CROSSSLOT Keys in request don‘t hash to the same slot
数据库·redis·哈希算法
Zfox_17 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
呼拉拉呼拉17 小时前
Redis内存淘汰策略
redis·缓存
咖啡啡不加糖21 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
MickeyCV21 小时前
使用Docker部署MySQL&Redis容器与常见命令
redis·mysql·docker·容器·wsl·镜像
肥仔哥哥19301 天前
springCloud2025+springBoot3.5.0+Nacos集成redis从nacos拉配置起服务
redis·缓存·最新boot3集成
呼拉拉呼拉1 天前
Redis故障转移
数据库·redis·缓存·高可用架构