Bootstrap

Spring Cache基础组件 CacheResolver

相关阅读

简介

定义解析被拦截方法调用使用的Cache实例的接口;

核心代码

/**
 * 解析被拦截方法调用使用的Cache实例
 */
Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context);

实现子类

public interface CacheResolver
    public abstract class AbstractCacheResolver implements CacheResolver, InitializingBean
        public class SimpleCacheResolver extends AbstractCacheResolver
        public class NamedCacheResolver extends AbstractCacheResolver

AbstractCacheResolver

简介

CacheResolver实现基础抽象类,定义了解析缓存的算法骨架,子类需要实现根据调用上下文获取缓存标识符集合;

核心代码

// 缓存管理器
private CacheManager cacheManager;


/**
 * 解析cache
 * 算法模板
 */
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
    // 获取待解析缓存的名称集合
    Collection<String> cacheNames = getCacheNames(context);
    if (cacheNames == null) {
        return Collections.emptyList();
    }
    Collection<Cache> result = new ArrayList<>(cacheNames.size());
    for (String cacheName : cacheNames) {
        // 根据缓存名称从缓存管理器获取缓存
        Cache cache = getCacheManager().getCache(cacheName);
        if (cache == null) {
            throw new IllegalArgumentException("Cannot find cache named '" +
        cacheName + "' for " + context.getOperation());
        }
        result.add(cache);
    }
    return result;
}

/**
 * 获取待解析缓存的名称
 * 算法细节,由子类实现
 */
@Nullable
protected abstract Collection<String> getCacheNames(CacheOperationInvocationContext<?> context);

SimpleCacheResolver

简介

基于缓存名称和可配置的缓存管理器CacheManager的简单实现;
缓存名称通过BasicOperation.getCacheNames获取;

核心代码

/**
 * 获取待解析缓存的名称
 */
@Override
protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
    // 直接调用缓存动作相关的缓存标识符
    return context.getOperation().getCacheNames();
}

/**
 * 根据给定的CacheManager返回SimpleCacheResolver实例
 */
@Nullable
static SimpleCacheResolver of(@Nullable CacheManager cacheManager) {
    return (cacheManager != null ? new SimpleCacheResolver(cacheManager) : null);
}

NamedCacheResolver

简介

基于可配置的缓存名称集合和可配置的缓存管理器CacheManager的简单实现;

核心代码

// 缓存名称集合
private Collection<String> cacheNames;


/**
 * 获取待解析缓存的名称
 */
@Override
protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
     return this.cacheNames;
}
;