標籤:blog java io 檔案 ar 資料 div cti 代碼
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; } }
該方法通過預設配置,以Factory 方法建立一個單例對象緩衝管理器
也可以通過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的一點理解,以後還會繼續補充
緩衝初解(二)