缓存bean

import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class ResourceCache {
private static ResourceCache instance = null;
private static Log log = LogFactory.getLog(ResourceCache.class);
private static Cache cache = null;
private static CacheManager manager = null;

/**
* Instantiates a new flash data cache.
*
* @throws Exception
*/
private ResourceCache() throws Exception {
try {
InputStream configFile = ResourceCache.class.getClassLoader()
.getResourceAsStream("ehcache.xml");
manager = CacheManager.create(configFile);
cache = manager.getCache("authorities");
} catch (Exception e) {
throw new Exception("得到cache失败!", e);
}
}

public static ResourceCache getInstance() throws Exception {

if (instance == null) {
instance = new ResourceCache();
// jvm关闭时才执行此钩子,但对象已经被�?��,会抛出空指�?
// Runtime.getRuntime().addShutdownHook(new Thread(){
// public void run(){
// FlashDataCache.manager.shutdown();
// }
// });
}
return instance;
}

public void putData(String key, Object value) {
try {
Element element = new Element(key, value);
cache.put(element);
cache.flush();
} catch (IllegalArgumentException e) {
log.error("放入缓存失败", e);
e.printStackTrace();
} catch (IllegalStateException e) {
log.error("放入缓存失败", e);
e.printStackTrace();
} catch (CacheException e) {
log.error("放入缓存失败", e);
e.printStackTrace();
}
}

public Object getData(String key) {
Object bean = null;
try {
Element element = cache.get(key);
if (element != null) {
bean = element.getValue();
}
} catch (IllegalStateException e) {
bean = null;
log.error("取出缓存失败", e);
e.printStackTrace();
} catch (CacheException e) {
bean = null;
log.error("取出缓存失败", e);
e.printStackTrace();
}
return bean;
}

public static void destroy() {
ResourceCache.manager.shutdown();
}

public static void main(String[] args) throws Exception {
ResourceCache.getInstance().putData("x", "chenghui");
System.out.println(ResourceCache.getInstance());
System.out.println(ResourceCache.getInstance());
System.out.println(ResourceCache.getInstance().getData("x"));
}

你可能感兴趣的:(缓存bean)