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中的Lua脚本,redis的事务机制
java·redis·lua
阿桢呀7 小时前
Redis实战篇《黑马点评》5
数据库·redis·缓存
01_7 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
Kerwin要坚持日更9 小时前
一文讲解Redis中的主从复制
数据库·redis·缓存
Suk-god9 小时前
【Redis】基础知识入门
数据库·redis·缓存
zfj3219 小时前
手动搭建Redis1主2从+ 3 Sentinel 高可用集群
redis·sentinel·高可用
m0_7482309410 小时前
Redis 通用命令
前端·redis·bootstrap
Struggle Sheep12 小时前
linux安装redis
linux·运维·redis
guihong00415 小时前
Redis 深度解析:高性能缓存与分布式数据存储的核心利器
redis·分布式·缓存
qq_5298353517 小时前
Redis作为缓存和数据库的数据一致性问题
数据库·redis·缓存