- 浏览: 148510 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
rong_wz:
...
error at ::0 can't find referenced pointcut...解决方法 -
tonydzl_2008:
这个与jdk 版本和 aspectj ,aspectjweav ...
error at ::0 can't find referenced pointcut...解决方法 -
wsmzyzn:
...
error at ::0 can't find referenced pointcut...解决方法 -
Mr.TianShu:
NSCoffee 写道方法确实不错,不过测试一下貌似最后给出的 ...
Hibernate抓取策略以及如何避免cannot simultaneously fetch multiple bags异常 -
Mr.TianShu:
//Default: FetchType.EAGER 默 ...
Hibernate抓取策略以及如何避免cannot simultaneously fetch multiple bags异常
文章出处http://lcllcl987.iteye.com/blog/222693
鉴于csdn的blog的不稳定, 及混乱的编辑器, 和无上传功能, 遂决定彻底投诚javaeye的blog.
数月前整理的一个东西, 作为cache的扫盲文档.参考了它的官方文档.
对ehcache感兴趣的兄台可以参考.
附件为eclipse项目, 直接导入, 运行test目录下的junit testcase, 可一目了然.
一 ehcache API:
1: Using the CacheManager
1.1所有ehcache的使用, 都是从 CacheManager. 开始的.
有多种方法创建CacheManager实例:
Java代码
//Create a singleton CacheManager using defaults, then list caches.
CacheManager.getInstance()
//Create a singleton CacheManager using defaults, then list caches.
CacheManager.getInstance()
或者:
Java代码
//Create a CacheManager instance using defaults, then list caches.
CacheManager manager = new CacheManager();
String[] cacheNames = manager.getCacheNames();
//Create a CacheManager instance using defaults, then list caches.
CacheManager manager = new CacheManager();
String[] cacheNames = manager.getCacheNames();
如果需要从指定配置文件创建 CacheManager:
Java代码
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();
1.2 Adding and Removing Caches Programmatically
手动创建一个cache, 而不是通过配置文件:
Java代码
//creates a cache called testCache, which
//will be configured using defaultCache from the configuration
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
//creates a cache called testCache, which
//will be configured using defaultCache from the configuration
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
或者:
Java代码
//Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
//been added to a CacheManager.
public void testCreatCacheByProgram()
{
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache testCache = singletonManager.getCache("testCache");
assertNotNull(testCache);
}
//Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
//been added to a CacheManager.
public void testCreatCacheByProgram()
{
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache testCache = singletonManager.getCache("testCache");
assertNotNull(testCache);
}
手动移除一个cache:
Java代码
//Remove cache called sampleCache1
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");
//Remove cache called sampleCache1
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");
1.3 Shutdown the CacheManager
ehcache应该在使用后关闭, 最佳实践是在code中显式调用:
Java代码
//Shutdown the singleton CacheManager
CacheManager.getInstance().shutdown();
//Shutdown the singleton CacheManager
CacheManager.getInstance().shutdown(); 2 Using Caches
比如我有这样一个cache:
Xml代码
<cache name="sampleCache1" maxElementsInMemory="10000"
maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
<cache name="sampleCache1" maxElementsInMemory="10000"
maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
2.1 Obtaining a reference to a Cache
获得该cache的引用:
Java代码
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
2.2 Performing CRUD operations
下面的代码演示了ehcache的增删改查:
Java代码
public void testCRUD()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
//Put an element into a cache
Element element = new Element("key1", "value1");
cache.put(element);
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));
//Get a Serializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
Serializable value = element.getValue();
//Get a NonSerializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
assertNotNull(element);
Object valueObj = element.getObjectValue();
assertNotNull(valueObj);
//Remove an element from a cache with a key of "key1".
assertNotNull(cache.get("key1"));
cache.remove("key1");
assertNull(cache.get("key1"));
}
public void testCRUD()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
//Put an element into a cache
Element element = new Element("key1", "value1");
cache.put(element);
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));
//Get a Serializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
Serializable value = element.getValue();
//Get a NonSerializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
assertNotNull(element);
Object valueObj = element.getObjectValue();
assertNotNull(valueObj);
//Remove an element from a cache with a key of "key1".
assertNotNull(cache.get("key1"));
cache.remove("key1");
assertNull(cache.get("key1"));
}
2.3 Disk Persistence on demand
Java代码
//sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
public void testDiskPersistence()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < 50000; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
cache.flush();
Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
}
//sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
public void testDiskPersistence()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < 50000; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
cache.flush();
Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
}
备注: 持久化到硬盘的路径由虚拟机参数"java.io.tmpdir"决定.
例如, 在windows中, 会在此路径下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常会在: /tmp 下
2.4 Obtaining Cache Sizes
以下代码演示如何获得cache个数:
Java代码
public void testCachesizes()
{
long count = 5;
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < count; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
//Get the number of elements currently in the Cache.
int elementsInCache = cache.getSize();
assertTrue(elementsInCache == 5);
//Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();
//Get the number of elements currently in the DiskStore.
long elementsInDiskStore = cache.getDiskStoreSize();
assertTrue(elementsInMemory + elementsInDiskStore == count);
}
public void testCachesizes()
{
long count = 5;
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < count; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
//Get the number of elements currently in the Cache.
int elementsInCache = cache.getSize();
assertTrue(elementsInCache == 5);
//Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();
//Get the number of elements currently in the DiskStore.
long elementsInDiskStore = cache.getDiskStoreSize();
assertTrue(elementsInMemory + elementsInDiskStore == count);
}
3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支持:
Java代码
CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
把该程序打包, 然后:
Java代码
java -Dcom.sun.management.jmxremote -jar 程序名.jar
java -Dcom.sun.management.jmxremote -jar 程序名.jar
再到javahome/bin中运行jconsole.exe, 便可监控cache.
4. 用户可以自定义处理cacheEventHandler, 处理诸如元素放入cache的各种事件(放入,移除,过期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory节点.
Java代码
<cache name="Test" maxElementsInMemory="1" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU">
<cacheEventListenerFactory class="co.ehcache.EventFactory" />
</cache>
<cache name="Test" maxElementsInMemory="1" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU">
<cacheEventListenerFactory class="co.ehcache.EventFactory" />
</cache>
4.2: 编写EventFactory, 继承CacheEventListenerFactory:
Java代码
public class EventFactory extends CacheEventListenerFactory
{
@Override
public CacheEventListener createCacheEventListener(Properties properties)
{
// TODO Auto-generated method stub
return new CacheEvent();
}
}
public class EventFactory extends CacheEventListenerFactory
{
@Override
public CacheEventListener createCacheEventListener(Properties properties)
{
// TODO Auto-generated method stub
return new CacheEvent();
}
}
4.3 编写 class: CacheEvent, 实现 CacheEventListener 接口:
Java代码
public class CacheEvent implements CacheEventListener
{
public void dispose()
{
log("in dispose");
}
public void notifyElementEvicted(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementEvicted" + element);
}
public void notifyElementExpired(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementExpired" + element);
}
public void notifyElementPut(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementPut" + element);
}
public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementRemoved" + element);
}
public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementUpdated" + element);
}
public void notifyRemoveAll(Ehcache cache)
{
// TODO Auto-generated method stub
log("in notifyRemoveAll");
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
private void log(String s)
{
Log.debug(s);
}
}
public class CacheEvent implements CacheEventListener
{
public void dispose()
{
log("in dispose");
}
public void notifyElementEvicted(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementEvicted" + element);
}
public void notifyElementExpired(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementExpired" + element);
}
public void notifyElementPut(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementPut" + element);
}
public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementRemoved" + element);
}
public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementUpdated" + element);
}
public void notifyRemoveAll(Ehcache cache)
{
// TODO Auto-generated method stub
log("in notifyRemoveAll");
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
private void log(String s)
{
Log.debug(s);
}
}
现在可以编写测试代码:
Java代码
public void testEventListener()
{
String key = "person";
Person person = new Person("lcl", 100);
MyCacheManager.getInstance().put("Test", key, person);
Person p = (Person) MyCacheManager.getInstance().get("Test", key);
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertNull(MyCacheManager.getInstance().get("Test", key));
}
public void testEventListener()
{
String key = "person";
Person person = new Person("lcl", 100);
MyCacheManager.getInstance().put("Test", key, person);
Person p = (Person) MyCacheManager.getInstance().get("Test", key);
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertNull(MyCacheManager.getInstance().get("Test", key));
}
根据配置, 该缓存对象生命期只有2分钟, 在Thread.sleep(10000)期间, 该缓存元素将过期被销毁, 在销毁前, 触发notifyElementExpired事件.
二 Ehcache配置文件
以如下配置为例说明:
Xml代码
<cache name="CACHE_FUNC"
maxElementsInMemory="2"
eternal="false"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120" />
<cache name="CACHE_FUNC"
maxElementsInMemory="2"
eternal="false"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120" />
maxElementsInMemory :cache 中最多可以存放的元素的数量。如果放入cache中的元素超过这个数值,有两种情况:
1. 若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。
2. 若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
eternal :是否永驻内存。如果值是true,cache中的元素将一直保存在内存中,不会因为时间超时而丢失,所以在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。
3. timeToIdleSeconds :访问这个cache中元素的最大间隔时间。如果超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
4. timeToLiveSeconds : cache中元素的生存时间。意思是从cache中的某个元素从创建到消亡的时间,从创建开始计时,当超过这个时间,这个元素将被从cache中清除。
5. overflowToDisk :溢出是否写入磁盘。系统会根据标签<diskStore path="java.io.tmpdir"/> 中path的值查找对应的属性值,如果系统的java.io.tmpdir的值是 D:\temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。
6. diskExpiryThreadIntervalSeconds :磁盘缓存的清理线程运行间隔.
7. memoryStoreEvictionPolicy :内存存储与释放策略。有三个值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time
diskPersistent : 是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
更多说明可看ehcache自带的ehcache.xml的注释说明.
鉴于csdn的blog的不稳定, 及混乱的编辑器, 和无上传功能, 遂决定彻底投诚javaeye的blog.
数月前整理的一个东西, 作为cache的扫盲文档.参考了它的官方文档.
对ehcache感兴趣的兄台可以参考.
附件为eclipse项目, 直接导入, 运行test目录下的junit testcase, 可一目了然.
一 ehcache API:
1: Using the CacheManager
1.1所有ehcache的使用, 都是从 CacheManager. 开始的.
有多种方法创建CacheManager实例:
Java代码
//Create a singleton CacheManager using defaults, then list caches.
CacheManager.getInstance()
//Create a singleton CacheManager using defaults, then list caches.
CacheManager.getInstance()
或者:
Java代码
//Create a CacheManager instance using defaults, then list caches.
CacheManager manager = new CacheManager();
String[] cacheNames = manager.getCacheNames();
//Create a CacheManager instance using defaults, then list caches.
CacheManager manager = new CacheManager();
String[] cacheNames = manager.getCacheNames();
如果需要从指定配置文件创建 CacheManager:
Java代码
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();
Create two CacheManagers, each with a different configuration, and list the caches in each.
CacheManager manager1 = new CacheManager("src/config/ehcache1.xml");
CacheManager manager2 = new CacheManager("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();
1.2 Adding and Removing Caches Programmatically
手动创建一个cache, 而不是通过配置文件:
Java代码
//creates a cache called testCache, which
//will be configured using defaultCache from the configuration
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
//creates a cache called testCache, which
//will be configured using defaultCache from the configuration
CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
或者:
Java代码
//Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
//been added to a CacheManager.
public void testCreatCacheByProgram()
{
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache testCache = singletonManager.getCache("testCache");
assertNotNull(testCache);
}
//Create a Cache and add it to the CacheManager, then use it. Note that Caches are not usable until they have
//been added to a CacheManager.
public void testCreatCacheByProgram()
{
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache testCache = singletonManager.getCache("testCache");
assertNotNull(testCache);
}
手动移除一个cache:
Java代码
//Remove cache called sampleCache1
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");
//Remove cache called sampleCache1
CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");
1.3 Shutdown the CacheManager
ehcache应该在使用后关闭, 最佳实践是在code中显式调用:
Java代码
//Shutdown the singleton CacheManager
CacheManager.getInstance().shutdown();
//Shutdown the singleton CacheManager
CacheManager.getInstance().shutdown(); 2 Using Caches
比如我有这样一个cache:
Xml代码
<cache name="sampleCache1" maxElementsInMemory="10000"
maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
<cache name="sampleCache1" maxElementsInMemory="10000"
maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"
timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" />
2.1 Obtaining a reference to a Cache
获得该cache的引用:
Java代码
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
2.2 Performing CRUD operations
下面的代码演示了ehcache的增删改查:
Java代码
public void testCRUD()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
//Put an element into a cache
Element element = new Element("key1", "value1");
cache.put(element);
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));
//Get a Serializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
Serializable value = element.getValue();
//Get a NonSerializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
assertNotNull(element);
Object valueObj = element.getObjectValue();
assertNotNull(valueObj);
//Remove an element from a cache with a key of "key1".
assertNotNull(cache.get("key1"));
cache.remove("key1");
assertNull(cache.get("key1"));
}
public void testCRUD()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
//Put an element into a cache
Element element = new Element("key1", "value1");
cache.put(element);
//This updates the entry for "key1"
cache.put(new Element("key1", "value2"));
//Get a Serializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
Serializable value = element.getValue();
//Get a NonSerializable value from an element in a cache with a key of "key1".
element = cache.get("key1");
assertNotNull(element);
Object valueObj = element.getObjectValue();
assertNotNull(valueObj);
//Remove an element from a cache with a key of "key1".
assertNotNull(cache.get("key1"));
cache.remove("key1");
assertNull(cache.get("key1"));
}
2.3 Disk Persistence on demand
Java代码
//sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
public void testDiskPersistence()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < 50000; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
cache.flush();
Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
}
//sampleCache1 has a persistent diskStore. We wish to ensure that the data //and index are written immediately.
public void testDiskPersistence()
{
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < 50000; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
cache.flush();
Log.debug("java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
}
备注: 持久化到硬盘的路径由虚拟机参数"java.io.tmpdir"决定.
例如, 在windows中, 会在此路径下
C:\Documents and Settings\li\Local Settings\Temp
在linux中, 通常会在: /tmp 下
2.4 Obtaining Cache Sizes
以下代码演示如何获得cache个数:
Java代码
public void testCachesizes()
{
long count = 5;
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < count; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
//Get the number of elements currently in the Cache.
int elementsInCache = cache.getSize();
assertTrue(elementsInCache == 5);
//Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();
//Get the number of elements currently in the DiskStore.
long elementsInDiskStore = cache.getDiskStoreSize();
assertTrue(elementsInMemory + elementsInDiskStore == count);
}
public void testCachesizes()
{
long count = 5;
String cacheName = "sampleCache1";
CacheManager manager = new CacheManager("src/ehcache1.xml");
Cache cache = manager.getCache(cacheName);
for (int i = 0; i < count; i++)
{
Element element = new Element("key" + i, "myvalue" + i);
cache.put(element);
}
//Get the number of elements currently in the Cache.
int elementsInCache = cache.getSize();
assertTrue(elementsInCache == 5);
//Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();
//Get the number of elements currently in the DiskStore.
long elementsInDiskStore = cache.getDiskStoreSize();
assertTrue(elementsInMemory + elementsInDiskStore == count);
}
3: Registering CacheStatistics in an MBeanServer
ehCache 提供jmx支持:
Java代码
CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
CacheManager manager = new CacheManager();
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true);
把该程序打包, 然后:
Java代码
java -Dcom.sun.management.jmxremote -jar 程序名.jar
java -Dcom.sun.management.jmxremote -jar 程序名.jar
再到javahome/bin中运行jconsole.exe, 便可监控cache.
4. 用户可以自定义处理cacheEventHandler, 处理诸如元素放入cache的各种事件(放入,移除,过期等事件)
只需三步:
4.1 在cache配置中, 增加cacheEventListenerFactory节点.
Java代码
<cache name="Test" maxElementsInMemory="1" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU">
<cacheEventListenerFactory class="co.ehcache.EventFactory" />
</cache>
<cache name="Test" maxElementsInMemory="1" eternal="false"
overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
diskPersistent="false" diskExpiryThreadIntervalSeconds="1"
memoryStoreEvictionPolicy="LFU">
<cacheEventListenerFactory class="co.ehcache.EventFactory" />
</cache>
4.2: 编写EventFactory, 继承CacheEventListenerFactory:
Java代码
public class EventFactory extends CacheEventListenerFactory
{
@Override
public CacheEventListener createCacheEventListener(Properties properties)
{
// TODO Auto-generated method stub
return new CacheEvent();
}
}
public class EventFactory extends CacheEventListenerFactory
{
@Override
public CacheEventListener createCacheEventListener(Properties properties)
{
// TODO Auto-generated method stub
return new CacheEvent();
}
}
4.3 编写 class: CacheEvent, 实现 CacheEventListener 接口:
Java代码
public class CacheEvent implements CacheEventListener
{
public void dispose()
{
log("in dispose");
}
public void notifyElementEvicted(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementEvicted" + element);
}
public void notifyElementExpired(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementExpired" + element);
}
public void notifyElementPut(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementPut" + element);
}
public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementRemoved" + element);
}
public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementUpdated" + element);
}
public void notifyRemoveAll(Ehcache cache)
{
// TODO Auto-generated method stub
log("in notifyRemoveAll");
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
private void log(String s)
{
Log.debug(s);
}
}
public class CacheEvent implements CacheEventListener
{
public void dispose()
{
log("in dispose");
}
public void notifyElementEvicted(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementEvicted" + element);
}
public void notifyElementExpired(Ehcache cache, Element element)
{
// TODO Auto-generated method stub
log("in notifyElementExpired" + element);
}
public void notifyElementPut(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementPut" + element);
}
public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementRemoved" + element);
}
public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException
{
// TODO Auto-generated method stub
log("in notifyElementUpdated" + element);
}
public void notifyRemoveAll(Ehcache cache)
{
// TODO Auto-generated method stub
log("in notifyRemoveAll");
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
private void log(String s)
{
Log.debug(s);
}
}
现在可以编写测试代码:
Java代码
public void testEventListener()
{
String key = "person";
Person person = new Person("lcl", 100);
MyCacheManager.getInstance().put("Test", key, person);
Person p = (Person) MyCacheManager.getInstance().get("Test", key);
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertNull(MyCacheManager.getInstance().get("Test", key));
}
public void testEventListener()
{
String key = "person";
Person person = new Person("lcl", 100);
MyCacheManager.getInstance().put("Test", key, person);
Person p = (Person) MyCacheManager.getInstance().get("Test", key);
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
assertNull(MyCacheManager.getInstance().get("Test", key));
}
根据配置, 该缓存对象生命期只有2分钟, 在Thread.sleep(10000)期间, 该缓存元素将过期被销毁, 在销毁前, 触发notifyElementExpired事件.
二 Ehcache配置文件
以如下配置为例说明:
Xml代码
<cache name="CACHE_FUNC"
maxElementsInMemory="2"
eternal="false"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120" />
<cache name="CACHE_FUNC"
maxElementsInMemory="2"
eternal="false"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
overflowToDisk="true"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120" />
maxElementsInMemory :cache 中最多可以存放的元素的数量。如果放入cache中的元素超过这个数值,有两种情况:
1. 若overflowToDisk的属性值为true,会将cache中多出的元素放入磁盘文件中。
2. 若overflowToDisk的属性值为false,会根据memoryStoreEvictionPolicy的策略替换cache中原有的元素。
eternal :是否永驻内存。如果值是true,cache中的元素将一直保存在内存中,不会因为时间超时而丢失,所以在这个值为true的时候,timeToIdleSeconds和timeToLiveSeconds两个属性的值就不起作用了。
3. timeToIdleSeconds :访问这个cache中元素的最大间隔时间。如果超过这个时间没有访问这个cache中的某个元素,那么这个元素将被从cache中清除。
4. timeToLiveSeconds : cache中元素的生存时间。意思是从cache中的某个元素从创建到消亡的时间,从创建开始计时,当超过这个时间,这个元素将被从cache中清除。
5. overflowToDisk :溢出是否写入磁盘。系统会根据标签<diskStore path="java.io.tmpdir"/> 中path的值查找对应的属性值,如果系统的java.io.tmpdir的值是 D:\temp,写入磁盘的文件就会放在这个文件夹下。文件的名称是cache的名称,后缀名的data。如:CACHE_FUNC.data。
6. diskExpiryThreadIntervalSeconds :磁盘缓存的清理线程运行间隔.
7. memoryStoreEvictionPolicy :内存存储与释放策略。有三个值:
LRU -least recently used
LFU -least frequently used
FIFO-first in first out, the oldest element by creation time
diskPersistent : 是否持久化磁盘缓存。当这个属性的值为true时,系统在初始化的时候会在磁盘中查找文件名为cache名称,后缀名为index的的文件,如CACHE_FUNC.index 。这个文件中存放了已经持久化在磁盘中的cache的index,找到后把cache加载到内存。要想把cache真正持久化到磁盘,写程序时必须注意,在是用net.sf.ehcache.Cache的void put (Element element)方法后要使用void flush()方法。
更多说明可看ehcache自带的ehcache.xml的注释说明.
发表评论
-
JPA知识汇总
2010-10-14 10:00 0JPA JPA全称Java Persistence API. ... -
从今天看是研究springside-3.3.4第一天:部署
2010-09-29 11:23 2787all-in-one版本太大,就不想下了,我下了一个src版, ... -
tomcat的启动内存设置
2010-09-21 16:20 1261其初始空间(即-Xms)是物理内存的1/64,最大空间(-Xm ... -
MyEclipse SVN插件 去掉或者修改以前记住的用户名和密码方法
2010-06-02 16:47 6883因为之前连的svn服务器中的项目的用户的权限 不能 满足我连接 ... -
Apache Commons-Configuration
2010-03-22 20:10 1535【文章出处】http://wangxi ... -
java反编译工具JD-GUI
2009-12-31 00:20 1554下载地址http://java.decompiler.free ... -
反编译工具JD-Eclipse的安装
2009-12-31 00:13 3140下载地址http://java.decompiler.free ... -
myeclipse8.0M1启动优化
2009-12-23 03:48 20911、老是弹出Quick update er ... -
myeclipse8.0M1注册码
2009-12-23 03:45 1563下载地址:注意请直接复制粘贴到迅雷! http://down ... -
学JFreeChart不得不看的中文API
2009-12-08 14:14 810JFreeChart类: void setAntiAl ... -
JPA是什么
2009-12-08 13:24 741文章出处http://www.blogjava ... -
关于J2EE Tranaction的几个基本概念
2009-11-26 19:01 933文章出处http://www.cnblogs.com/perh ... -
什么是JTA
2009-11-26 18:58 2537Java Transaction API(Java事务API) ... -
什么是事务transaction
2009-11-26 18:14 1435文章出处http://zht1933.itey ... -
关于什么是Java Bean的整理
2009-11-19 18:41 2477JavaBean是描述Java的软件组件模型,有点类似于Mic ... -
Java创建对象实例的三种方法
2009-11-15 00:49 1448Java有一下三种方法可以创建对象实例。 1.new 通常 ... -
Mysql 查看连接数,状态
2009-11-10 06:43 1390命令: show processlist; 如果是root帐 ... -
制作可执行的JAR文件包以及JAR命令详解
2009-07-10 10:25 720常常在网上看到有人询 ...
相关推荐
EhCache是一个开源的Java缓存框架,常用于提高应用程序的性能和响应速度。它能够存储数据在内存中,使得频繁访问的数据可以更快地被获取,从而减少对数据库的依赖和压力。EhCache分为本地缓存和分布式缓存两种模式,...
本文将详细讲解"cache/ehcache缓存使用"的相关知识点,包括缓存的基本概念、Ehcache的介绍、以及如何在Java应用中使用Ehcache进行缓存操作。 首先,我们要理解什么是缓存。缓存是一种存储技术,它临时存储常用或...
该函数基于MyBlob 工具箱,用于创建测试环境从现有数据库中复制固定数量的元素源数据库的eache表来测试一个。 我与 MyBlob Toolbox 的作者无关:如果你不喜欢这个功能,那是我的错,而不是他的错。 myblob_testdb...
例如:Each,EachE,List,SortedList等。 安装 使用go get命令获取最新版本 go get github.com/SeananXu/go-set 用以下命令导入: import "github.com/SeananXu/go-set" 并在代码中使用set作为包名称。 例子 ...
Console.WriteLine($"Error: {eachE.Message}"); return true; }); }, TaskContinuationOptions.OnlyOnFaulted); faultedTask.Wait(); } ``` 在上面的代码中,我们使用ContinueWith方法来捕捉前驱任务中的异常...