首页 > 代码库 > 缓存初解(二)

缓存初解(二)

EHCAche源码分析:

首先看缓存类CacheManager

public class CacheManager {  //该类在默认情况下读取CLASSPATH下的ehcache.xml文件,并且是单例模式创建新的缓存类    /**     * Keeps track of all known CacheManagers. Used to check on conflicts.     * CacheManagers should remove themselves from this list during shut down.     */    public static final List ALL_CACHE_MANAGERS = Collections.synchronizedList(new ArrayList());    private static final Log LOG = LogFactory.getLog(CacheManager.class.getName());    /**     * The Singleton Instance.     */    private static CacheManager singleton;    /**     * Caches managed by this manager.     */    protected final Map caches = new HashMap();    /**     * Default cache cache.     */    private Ehcache defaultCache;

调用该类需要CacheManager manager = new VacheManager();

新建一个就要:manager.create();

   public static CacheManager create() throws CacheException {        synchronized (CacheManager.class) {            if (singleton == null) {                if (LOG.isDebugEnabled()) {                    LOG.debug("Creating new CacheManager with default config");                }                singleton = new CacheManager();            } else {                if (LOG.isDebugEnabled()) {                    LOG.debug("Attempting to create an existing singleton. Existing singleton returned.");                }            }            return singleton;        }    }

 该方法通过默认配置,以工厂方法创建一个单例对象缓存管理器

也可以通过getInstance()来获取实例

  public static CacheManager getInstance() throws CacheException {        return CacheManager.create();    }

 根据缓存名称获取缓存对象

  public synchronized Cache getCache(String name) throws IllegalStateException, ClassCastException {        checkStatus();        return (Cache) caches.get(name);    }

 缓存是以Map集合存储数据的,也可以通过

 public synchronized Ehcache getEhcache(String name) throws IllegalStateException {        checkStatus();        return (Ehcache) caches.get(name);    }

 来获取EHcache

那缓存是如何存储的呢,看以下代码就知道了

   public synchronized void addCache(String cacheName) throws IllegalStateException,            ObjectExistsException, CacheException {        checkStatus();        //NPE guard        if (cacheName == null || cacheName.length() == 0) {            return;        }        if (caches.get(cacheName) != null) {            throw new ObjectExistsException("Cache " + cacheName + " already exists");        }        Ehcache cache = null;        try {            cache = (Ehcache) defaultCache.clone();        } catch (CloneNotSupportedException e) {            LOG.error("Failure adding cache. Initial cause was " + e.getMessage(), e);        }        if (cache != null) {            cache.setName(cacheName);        }        addCache(cache);    }

 通过addCache()方法,判断cacheName是否已经存在,如果不存在,那就在默认缓存中克隆clone()到cache里面,也就是map里面。如果存在就不做处理

以上是我对EHCache的一点理解,以后还会继续补充

缓存初解(二)