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

相关推荐
小小工匠2 小时前
Redis - 事务机制:能实现 ACID 属性吗
数据结构·redis·性能优化·并发·持久化
ofoxcoding3 小时前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen5 小时前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans6 小时前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时8 小时前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚8 小时前
Linux——Redis
数据库·redis·缓存
csjane10798 小时前
Redisson 限流原理
java·redis
ThanksGive9 小时前
Go 服务里的 Redis 锁惊群问题:一次本地合流优化实践
redis
小挪号底迪滴9 小时前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存