RedisCacheManager基本运作流程
其中底层数据处理可以是redis、ehcache
源码分析
RedisCacheManager继承关系:
其中主要是org.springframework.cache.support.AbstractCacheManager这个类
cacheMap
存储所有的缓存的集合,key为缓存名称,value为缓存cache
initializeCaches()
初始化缓存的静态配置
public void initializeCaches() {
// 调用loadCaches方法读取用户配置的缓存
Collection<? extends Cache> caches = loadCaches();
synchronized (this.cacheMap) {
this.cacheNames = Collections.emptySet();
this.cacheMap.clear();
Set<String> cacheNames = new LinkedHashSet<>(caches.size());
for (Cache cache : caches) {
String name = cache.getName();
this.cacheMap.put(name, decorateCache(cache));
cacheNames.add(name);
}
this.cacheNames = Collections.unmodifiableSet(cacheNames);
}
}
getCache()
获取对应的配置 其中getMissingCache是获取没有定义的cache
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache != null) {
return cache;
}
else {
// Fully synchronize now for missing cache creation...
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = getMissingCache(name);
if (cache != null) {
cache = decorateCache(cache);
this.cacheMap.put(name, cache);
updateCacheNames(name);
}
}
return cache;
}
}
}
getMissingCache()
如果此类缓存不存在或无法动态创建,则返回具有指定 name或null的缺失缓存。 如果本机提供程序支持它,则可能会在运行时创建一些缓存。如果按名称查找不会产生任何结果,则子类有机会在运行时注册此类缓存。返回的缓存将自动添加到此实例。
配置使用
构造方法
public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
Map<String, RedisCacheConfiguration> initialCacheConfigurations, boolean allowInFlightCacheCreation) {
this(cacheWriter, defaultCacheConfiguration, allowInFlightCacheCreation);
Assert.notNull(initialCacheConfigurations, "InitialCacheConfigurations must not be null!");
this.initialCacheConfiguration.putAll(initialCacheConfigurations);
}
cacheWriter: 操作redis的对象
defaultCacheConfiguration: 缓存默认配置
initialCacheConfigurations: 自定义缓存配置
allowInFlightCacheCreation: 如果设置为 false,则此缓存管理器仅限于初始缓存配置,并且不会在运行时创建新缓存。
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//用户自定义缓存
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
cacheConfigurations.put(ShiroSecurityConstants.SHIRO_ACTIVE_SESSIONS_NAME, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(30)));
cacheConfigurations.put(ShiroSecurityConstants.SHIRO_AUTHORIZATION_NAME, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(30)));
cacheConfigurations.put(ShiroSecurityConstants.TOKEN_CACHE_NAME, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)));
cacheConfigurations.put(ShiroSecurityConstants.VERIFICATION_CODE_CACHE_NAME, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)));
//默认缓存配置
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5)); // 设置缓存有效期5分钟
return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),redisCacheConfiguration,cacheConfigurations);
}