EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。EhCache 具有以下特点(摘自开源中国社区)。
public Cache(String name,
int maxElementsInMemory,
boolean overflowToDisk,
boolean eternal,
long timeToLiveSeconds,
long timeToIdleSeconds)
该构造函数是 EhCache 1.0 版本中的出现的,后续开发到 2.0 之后,出现了带有 CacheConfiguration 参数的构造函数,用法更强大。比如如下这个:
public Cache(CacheConfiguration cacheConfiguration,
RegisteredEventListeners registeredEventListeners,
BootstrapCacheLoader bootstrapCacheLoader)
用法可参见 EhCache 的 API Docs。
name - 缓存的名称,
default`保留为默认缓存名称;maxElementsInMemory
- 内存中的最大同时缓存元素个数;overflowToDisk
- 是否持久化(使用磁盘);eternal
- 对象是否永久有效(永不过期);timeToLiveSeconds
- 对象从其创建开始计算的生存时间(秒);timeToIdleSeconds
- 对象从其最后一次被访问开始计算的生存时间(秒)。一般来说,只有 name
、maxElementsInMemory
和 timeToLiveSeconds
显式设置,其他的参数常根据其不同的类型而设置为 false
、0
等。
public final void put(Element element)
throws IllegalArgumentException,
IllegalStateException,
CacheException
public final Element get(Object key)
throws IllegalStateException,
CacheException
public final boolean remove(Object key)
throws IllegalStateException
package com.sinosuperman.ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
public class Test {
public static void main(String[] args) {
String name = "Namespace";
int capacity = 500;
int refreshPeriod = 5000;
// Initialize EhCache
Cache cache = new Cache(name, capacity, false, false, refreshPeriod, 0);
cache.initialise();
System.out.println(
"Initialize EhCache: " +
" name: " + name +
" capacity: " + capacity +
" expire: " + refreshPeriod
);
// Set data into EhCache
String key1 = "Key";
String value1 = "Value";
Element element1 = new Element(key1, value1);
cache.put(element1);
System.out.println("Set (" + key1 + ", " + value1 + ") into EhCache.");
// Get data from EhCache
Element element2 = cache.get(key1);
String key2 = (String) element2.getObjectKey();
String value2 = (String) element2.getObjectValue();
System.out.println("Get (" + key2 + ", " + value2 + ") from EhCache.");
// Remove data from EhCache
if (cache.remove(key2)) {
System.out.println("Remove data with key = " + key2 + " successfully.");
}
// Get EhCache size
System.out.println("EhCache size is " + cache.getSize());
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Initialize EhCache: name: Namespace capacity: 500 expire: 5000
Set (Key, Value) into EhCache.
Get (Key, Value) from EhCache.
Remove data with key = Key successfully.
EhCache size is 0
可以登陆 EhCache.org,他们的文档还蛮多的。Enjoy EhCache!
-
转载请注明来自“柳大的CSDN博客”: blog.CSDN.net/Poechant
-