缓存bean

importjava.io.InputStream;

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

importnet.sf.ehcache.Cache;

importnet.sf.ehcache.CacheException;

importnet.sf.ehcache.CacheManager;

importnet.sf.ehcache.Element;

publicclassResourceCache{

privatestaticResourceCacheinstance=null;

privatestaticLoglog=LogFactory.getLog(ResourceCache.class);

privatestaticCachecache=null;

privatestaticCacheManagermanager=null;

/**

*Instantiatesanewflashdatacache.

*

*@throwsException

*/

privateResourceCache()throwsException{

try{

InputStreamconfigFile=ResourceCache.class.getClassLoader()

.getResourceAsStream("ehcache.xml");

manager=CacheManager.create(configFile);

cache=manager.getCache("authorities");

}catch(Exceptione){

thrownewException("得到cache失败!",e);

}

}

publicstaticResourceCachegetInstance()throwsException{

if(instance==null){

instance=newResourceCache();

//jvm关闭时才执行此钩子,但对象已经被�?��,会抛出空指�?

//Runtime.getRuntime().addShutdownHook(newThread(){

//publicvoidrun(){

//FlashDataCache.manager.shutdown();

//}

//});

}

returninstance;

}

publicvoidputData(Stringkey,Objectvalue){

try{

Elementelement=newElement(key,value);

cache.put(element);

cache.flush();

}catch(IllegalArgumentExceptione){

log.error("放入缓存失败",e);

e.printStackTrace();

}catch(IllegalStateExceptione){

log.error("放入缓存失败",e);

e.printStackTrace();

}catch(CacheExceptione){

log.error("放入缓存失败",e);

e.printStackTrace();

}

}

publicObjectgetData(Stringkey){

Objectbean=null;

try{

Elementelement=cache.get(key);

if(element!=null){

bean=element.getValue();

}

}catch(IllegalStateExceptione){

bean=null;

log.error("取出缓存失败",e);

e.printStackTrace();

}catch(CacheExceptione){

bean=null;

log.error("取出缓存失败",e);

e.printStackTrace();

}

returnbean;

}

publicstaticvoiddestroy(){

ResourceCache.manager.shutdown();

}

publicstaticvoidmain(String[]args)throwsException{

ResourceCache.getInstance().putData("x","chenghui");

System.out.println(ResourceCache.getInstance());

System.out.println(ResourceCache.getInstance());

System.out.println(ResourceCache.getInstance().getData("x"));

}

相关推荐