天天看點

BigMemory系列文章--4.Ehcache重要類和常用API轉載請注明出處哈:http://carlosfu.iteye.com/blog/2237511  

1. CacheManager: 管理Cache

2. Cache: 管理K-V緩存對象

3. Element: K-V緩存對象

下面這張圖形象表現三者的關系:

BigMemory系列文章--4.Ehcache重要類和常用API轉載請注明出處哈:http://carlosfu.iteye.com/blog/2237511  

二、Ehcache常用API

1. 建立CacheManager有多種方法:

CacheManager.newInstance(Configuration configuration) – Create a new CacheManager or return the existing one named in the configuration.(非單例)
CacheManager.create() – Create a new singleton CacheManager with default configuration, or return the existing singleton. This is the same as CacheManager.getInstance().(單例)
CacheManager.create(Configuration configuration) – Create a singleton CacheManager with the passed-in configuration, or return the existing singleton.(單例)
new CacheManager(Configuration configuration) – Create a new CacheManager, or throw an exception if the CacheManager named in the configuration already exists or if the parameter (configuration) is null.(非單例)      

實際應用建議使用第三種:CacheManager.create(Configuration configuration)

CacheManager cacheManager = CacheManager.create(BaseTest.class.getClassLoader().getResourceAsStream("ehcache.xml"));
//加入jmx
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheManager, mBeanServer, true, true, true, true);        
Cache cache = cacheManager.getCache("yourCacheName");      

2. Cache常用API

(1) 添加和更新key-value
//add
cache.put(new Element("key1", "value1")); 
//This updates the entry for "key1" 
cache.put(new Element("key1", "value2"));      
(2) 擷取key-value:
The following gets a Serializable value from an element with a key of key1.
Cache cache = manager.getCache("sampleCache1"); 
Element element = cache.get("key1"); 
Serializable value = element.getValue();
 
The following gets a NonSerializable value from an element with a key of key1.
Cache cache = manager.getCache("sampleCache1"); 
Element element = cache.get("key1"); 
Object value = element.getObjectValue();      
(3) 删除key-value:
cache.remove("key1");      
(4)擷取cache大小:
The following gets the number of elements currently in the cache.
int elementsInMemory = cache.getSize();
 
The following gets the number of elements currently in the MemoryStore.
long elementsInMemory = cache.getMemoryStoreSize();
 
 
The following gets the number of elements currently in the DiskStore.
long elementsOnDisk = cache.getDiskStoreSize();      
(5)擷取記憶體使用情況(生産環境不用使用,影響性能):
cache.calculateInMemorySize()      
(6) 判斷key是否過期:
boolean isExpired = cache.isExpired(Element element)      
(7) 擷取統計資訊:
StatisticsGateway statisticsGateway = ehcache.getStatistics();       
(8) 批量添加:
void putAll(Collection<Element> elements)      
(9) 批量擷取:
Map<Object,Element> getAll(Collection<?> keys)      
(10) 判斷key的位置:
boolean isElementInMemory(Object key)
boolean isElementOnDisk(Object key)      

繼續閱讀