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 天前
MongoDB 性能调优:十大实战经验总结 详细介绍
数据库·spring boot·mongodb·spring cloud·缓存·硬件架构
CHANG_THE_WORLD1 天前
C++ 并发编程指南 实现无锁队列
开发语言·c++·缓存·无锁队列·无锁编程
努力努力再努力wz1 天前
【c++进阶系列】:万字详解AVL树(附源码实现)
java·运维·开发语言·c++·redis
egoist20231 天前
[linux仓库]性能加速的隐形引擎:深度解析Linux文件IO中的缓冲区奥秘
linux·运维·开发语言·缓存·缓冲区
失散131 天前
并发编程——17 CPU缓存架构详解&高性能内存队列Disruptor实战
java·缓存·架构·并发编程
郭俊强1 天前
nestjs 缓存配置及防抖拦截器
缓存·nestjs·防抖
only-qi1 天前
146. LRU 缓存
java·算法·缓存
酷ku的森2 天前
Redis中的hash数据类型
数据库·redis·哈希算法
Arva .2 天前
Redis
数据库·redis·缓存
博一波2 天前
Redis 集群:连锁银行的 “多网点智能协作系统”
数据库·redis·缓存