Java Ecache缓存工具类源代码复制到编译器,调用即可:
public class EcacheUtil {
public static CacheManager manager = CacheManager.getInstance();//找到ehcache.xml的路径
public static Cache cache = manager.getCache("cache");//cache 的值取的是ehcache.xml中的name
/**
* 根据key查找缓存
* @param key
* @return
*/
public static Object getObjectCached(String key){
Element element1 = cache.get(key);
if(element1==null){
return null;
}else{
return element1.getValue();
}
}
/**
* 添加缓存
* @param key
* @param value
*/
public static void setObjectCached(String key,Object value){
cache.put(new Element(key, value));
}
/**
* 删除全部缓存
*/
public static void delObjectCachedall(){
cache.removeAll();
}
/**
* 卸载缓存
*/
public static void xiezaiObjectCached(){
manager.shutdown();
}
}
调用里面的方法事例:
//查找
public void main(){
Object cachevalue=EcacheUtil.getObjectCached("key");
if(cachevalue!=null){
System.out.println("key里面保存的值:"+cachevalue.toString());
}else{
System.out.println("key还没有添加到cache缓存中!");
}
}
//添加
public void main2(){
EcacheUtil.setObjectCached("key", "来自淘拜网!");
}