Ecache是一个基于纯Java进程的内存缓存框架,被用于开源的orm框架hibernate上,是一个开源的分布式缓存。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
我们可以利用ecache根据自己需要通过封装Ecache,实现站点的缓存功能。
public interface SimpleCache<K, V> {
V get(K key);
void put(K key, V value);
boolean remove(K key);
void clear();
boolean containsKey(K key);
}
public class Ehcache<K, V> implements SimpleCache<K, V>{
static CacheManager manager = CacheManager.create();
private Cache store;
public Ehcache(String name) {
store = new Cache(name, 100, false, false, 3600, 300);
manager.addCache(store);
}
public Ehcache(String name, int size) {
store = new Cache(name, size, false, false, 3600, 300);
manager.addCache(store);
}
public Ehcache(String name, int size, int ttl) {
store = new Cache(name, size, false, false, ttl, 300);
manager.addCache(store);
}
@SuppressWarnings("unchecked")
public V get(K key) {
Element e = store.get(key);
if ( e!= null ) {
return (V) e.getValue();
}
return null;
}
public void put(K key, V value) {
Element element = new Element(key, value);
store.put(element);
}
public boolean remove(K key) {
return store.remove(key);
}
@Override
public boolean containsKey(K key) {
return store.isKeyInCache(key);
}
@Override
public void clear() {
store.removeAll();
}
}
static SimpleCache<String, Object> codeList = new Ehcache<String, Object>("codeList", 10);
codeList.get(key)