Java缓存框架 EhCache EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
JAVA实例:
package test.ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class TestCache {
public static void main(String[] args) {
/**
* Create a singleton CacheManager using defaults, then list caches.
*/
CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();
System.out.println(cacheNames.length);
/**
* Create one CacheManager with a configuration, and list the caches in each.
*/
CacheManager manager2 = CacheManager.newInstance("ehcache1.xml");
String[] cacheNames2 = manager2.getCacheNames();
System.out.println(cacheNames2.length);
/**
* 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.
*/
CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache cache = singletonManager.getCache("testCache");
Element element = new Element("key1","value1");
cache.put(element);
Element value = cache.get("key1");
System.out.println(value.getObjectValue());
//value1
System.out.println(value.toString());
//[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1359130974484, LastAccessTime = 1359130974500 ]
}
}
配置文件ehcache1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="user.dir" />
<defaultCache
name="default-cache"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="1200"
timeToLiveSeconds="1200">
</defaultCache>
<cache
name="my-cache"
maxElementsInMemory="10000"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="true"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="FIFO">
</cache>
</ehcache>
<!--
Default Cache configuration. These will applied to caches programmatically created through the CacheManager.
The following attributes are required for defaultCache:
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
-->