本文主要研究一下jetcache的CacheManager

CacheManager

jetcache-core/src/main/java/com/alicp/jetcache/CacheManager.java

public interface CacheManager {
    <K, V> Cache<K, V> getCache(String area, String cacheName);

    void putCache(String area, String cacheName, Cache cache);

    BroadcastManager getBroadcastManager(String area);

    void putBroadcastManager(String area, BroadcastManager broadcastManager);

    default <K, V> Cache<K, V> getCache(String cacheName) {
        return getCache(CacheConsts.DEFAULT_AREA, cacheName);
    }

    default void putCache(String cacheName, Cache cache){
        putCache(CacheConsts.DEFAULT_AREA, cacheName, cache);
    }

    /**
     * create or get Cache instance.
     * @see QuickConfig#newBuilder(String)
     */
    <K, V> Cache<K, V> getOrCreateCache(QuickConfig config);

    default void putBroadcastManager(BroadcastManager broadcastManager){
        putBroadcastManager(CacheConsts.DEFAULT_AREA, broadcastManager);
    }

}
CacheManager定义了getCache、putCache、getBroadcastManager、putBroadcastManager、getOrCreateCache方法,并提供了aera为default的默认getCache、putCache、putBroadcastManager方法

SimpleCacheManager

jetcache-core/src/main/java/com/alicp/jetcache/SimpleCacheManager.java

public class SimpleCacheManager implements CacheManager, AutoCloseable {

    private static final boolean DEFAULT_CACHE_NULL_VALUE = false;

    private static final Logger logger = LoggerFactory.getLogger(SimpleCacheManager.class);

    // area -> cacheName -> Cache
    private final ConcurrentHashMap<String, ConcurrentHashMap<String, Cache>> caches = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, BroadcastManager> broadcastManagers = new ConcurrentHashMap();

    private CacheBuilderTemplate cacheBuilderTemplate;

    public SimpleCacheManager() {
    }

    @PreDestroy
    @Override
    public void close() {
        broadcastManagers.forEach((area, bm) -> {
            try {
                bm.close();
            } catch (Exception e) {
                logger.error("error during close broadcast manager", e);
            }
        });
        broadcastManagers.clear();
        caches.forEach((area, areaMap) -> {
            areaMap.forEach((cacheName, cache) -> {
                try {
                    cache.close();
                } catch (Exception e) {
                    logger.error("error during close Cache", e);
                }
            });
        });
        caches.clear();
    }

    private ConcurrentHashMap<String, Cache> getCachesByArea(String area) {
        return caches.computeIfAbsent(area, (key) -> new ConcurrentHashMap<>());
    }

    @Override
    public Cache getCache(String area, String cacheName) {
        ConcurrentHashMap<String, Cache> areaMap = getCachesByArea(area);
        return areaMap.get(cacheName);
    }

    @Override
    public void putCache(String area, String cacheName, Cache cache) {
        ConcurrentHashMap<String, Cache> areaMap = getCachesByArea(area);
        areaMap.put(cacheName, cache);
    }

    @Override
    public BroadcastManager getBroadcastManager(String area) {
        return broadcastManagers.get(area);
    }

    @Override
    public void putBroadcastManager(String area, BroadcastManager broadcastManager) {
        broadcastManagers.put(area, broadcastManager);
    }

    public CacheBuilderTemplate getCacheBuilderTemplate() {
        return cacheBuilderTemplate;
    }

    public void setCacheBuilderTemplate(CacheBuilderTemplate cacheBuilderTemplate) {
        this.cacheBuilderTemplate = cacheBuilderTemplate;
    }

    @Override
    public <K, V> Cache<K, V> getOrCreateCache(QuickConfig config) {
        if (cacheBuilderTemplate == null) {
            throw new IllegalStateException("cacheBuilderTemplate not set");
        }
        Objects.requireNonNull(config.getArea());
        Objects.requireNonNull(config.getName());
        ConcurrentHashMap<String, Cache> m = getCachesByArea(config.getArea());
        Cache c = m.get(config.getName());
        if (c != null) {
            return c;
        }
        return m.computeIfAbsent(config.getName(), n -> create(config));
    }

    //......
}    
SimpleCacheManager实现了CacheManager及AutoCloseable接口,其close方法先遍历broadcastManagers、caches执行其close方法然后进行clear;它在内存中维护了caches及broadcastManagers的ConcurrentHashMap,其getOrCreateCache主要根据QuickConfig来创建Cache,支持buildRemote、buildLocal以及multiLevelCache,并支持包装为RefreshCache或者LoadingCache,另外也支持设置cachePenetrationProtect以及CacheMonitor

buildLocal

    private Cache buildLocal(QuickConfig config) {
        EmbeddedCacheBuilder cacheBuilder = (EmbeddedCacheBuilder) cacheBuilderTemplate.getCacheBuilder(0, config.getArea());
        if (cacheBuilder == null) {
            throw new CacheConfigException("no local cache builder: " + config.getArea());
        }

        if (config.getLocalLimit() != null && config.getLocalLimit() > 0) {
            cacheBuilder.setLimit(config.getLocalLimit());
        }
        if (config.getCacheType() == CacheType.BOTH &&
                config.getLocalExpire() != null && config.getLocalExpire().toMillis() > 0) {
            cacheBuilder.expireAfterWrite(config.getLocalExpire().toMillis(), TimeUnit.MILLISECONDS);
        } else if (config.getExpire() != null && config.getExpire().toMillis() > 0) {
            cacheBuilder.expireAfterWrite(config.getExpire().toMillis(), TimeUnit.MILLISECONDS);
        }
        if (config.getKeyConvertor() != null) {
            cacheBuilder.getConfig().setKeyConvertor(config.getKeyConvertor());
        }
        cacheBuilder.setCacheNullValue(config.getCacheNullValue() != null ?
                config.getCacheNullValue() : DEFAULT_CACHE_NULL_VALUE);
        return cacheBuilder.buildCache();
    }
buildLocal通过cacheBuilderTemplate.getCacheBuilder获取EmbeddedCacheBuilder,然后支持设置limit、expireAfterWrite、keyConvertor、cacheNullValue

buildRemote

    private Cache buildRemote(QuickConfig config) {
        ExternalCacheBuilder cacheBuilder = (ExternalCacheBuilder) cacheBuilderTemplate
                .getCacheBuilder(1, config.getArea());
        if (cacheBuilder == null) {
            throw new CacheConfigException("no remote cache builder: " + config.getArea());
        }

        if (config.getExpire() != null && config.getExpire().toMillis() > 0) {
            cacheBuilder.expireAfterWrite(config.getExpire().toMillis(), TimeUnit.MILLISECONDS);
        }

        String prefix;
        if (config.getUseAreaInPrefix() != null && config.getUseAreaInPrefix()) {
            prefix = config.getArea() + "_" + config.getName();
        } else {
            prefix = config.getName();
        }
        if (cacheBuilder.getConfig().getKeyPrefixSupplier() != null) {
            Supplier<String> supplier = cacheBuilder.getConfig().getKeyPrefixSupplier();
            cacheBuilder.setKeyPrefixSupplier(() -> supplier.get() + prefix);
        } else {
            cacheBuilder.setKeyPrefix(prefix);
        }

        if (config.getKeyConvertor() != null) {
            cacheBuilder.getConfig().setKeyConvertor(config.getKeyConvertor());
        }
        if (config.getValueEncoder() != null) {
            cacheBuilder.getConfig().setValueEncoder(config.getValueEncoder());
        }
        if (config.getValueDecoder() != null) {
            cacheBuilder.getConfig().setValueDecoder(config.getValueDecoder());
        }

        cacheBuilder.setCacheNullValue(config.getCacheNullValue() != null ?
                config.getCacheNullValue() : DEFAULT_CACHE_NULL_VALUE);
        return cacheBuilder.buildCache();
    }
buildRemote方法通过cacheBuilderTemplate.getCacheBuilder获取ExternalCacheBuilder,然后支持设置expireAfterWrite、keyPrefix、keyConvertor、valueEncoder、valueDecoder、cacheNullValue

小结

CacheManager定义了getCache、putCache、getBroadcastManager、putBroadcastManager、getOrCreateCache方法,并提供了aera为default的默认getCache、putCache、putBroadcastManager方法;SimpleCacheManager实现了CacheManager及AutoCloseable接口,其close方法先遍历broadcastManagers、caches执行其close方法然后进行clear;它在内存中维护了caches及broadcastManagers的ConcurrentHashMap,其getOrCreateCache主要根据QuickConfig来创建Cache,支持buildRemote、buildLocal以及multiLevelCache,并支持包装为RefreshCache或者LoadingCache,另外也支持设置cachePenetrationProtect以及CacheMonitor。


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...