BigMemory系列文章--4.Ehcache重要类和常用API

1. CacheManager: 管理Cache

2. Cache: 管理K-V缓存对象

3. Element: K-V缓存对象

下面这张图形象表现三者的关系:

BigMemory系列文章--4.Ehcache重要类和常用API
 

二、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)

 

上一篇:BigMemroy系列文章--10.BigMemory监控系统(TMC)搭建


下一篇:C++雾中风景1:友元类与面向对象