各位大哥,幫忙解決一下這個問題

tianhandigeng發表於2010-12-14
我從xml中讀取資訊以後,放入到ehcache中,再次讀取的時候,如果存在之前放入的key就從cache中讀取,如果不存在就從xml檔案中讀取,程式碼是這樣的

public Object get(Class classObj, String nodeName, String fileName) {
Object obj = null;

if (ehcacheVindicator.getCache().isKeyInCache(nodeName)) {
Element element = ehcacheVindicator.getCache().get(nodeName);
if (ehcacheVindicator.getCache().isExpired(element))
obj = readObject(classObj, fileName, nodeName);// read object
// from xml
// file
else
obj = getObject(nodeName); // get object from cache
} else {
obj = readObject(classObj, fileName, nodeName); // read object from
// xml file
addObject(nodeName, obj); // add object to cache
}
return obj;
}

建立cache是這樣的

try {
this.cacheManager = CacheManager.create();
cache = cacheManager.getCache(cacheName);
} catch (Exception e) {
System.err
.println("Erroring creating CacheManager or isn't exisit the specifid cache");
}

測試程式碼是這樣的:

public static void main(String[] args) {
// TODO Auto-generated method stub
EhcacheVindicatorProxy proxy=new EhcacheVindicatorProxy("menu");
List list=(List)proxy.get(FrontMenu.class, "frontmenus", "menus.xml");
for(int i=0;i<list.size();i++){
FrontMenu front=(FrontMenu)list.get(i);
System.out.println(front.getName());
System.out.println(front.getHref());
System.out.println(front.getDisplay());
}
}



奇怪的是每次讀取都還是從xml檔案中讀取,壓根就不從cache中讀取,每次遮掩

this.cacheManager = CacheManager.create();
cache = cacheManager.getCache(cacheName);

System.out.println(cache.getSize());


輸出cache的快取都是0,也就是說沒放入進去,但是上面第一段程式碼 第一次執行的時候我已經這樣操作了

obj = readObject(classObj, fileName, nodeName); // read object from
// xml file
addObject(nodeName, obj); // add object to cache


我addObject了,進而操作就是cache.put(nodeName,obj);,這已經是放入了,為什麼我第二次讀取的時候cache還是空,還是從xml中讀取?希望高手指教一下

相關文章