简单Ehcahe封装
发布时间:2020-05-24 21:00:40 所属栏目:Java 来源:互联网
导读:简单Ehcahe封装
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。
import java.io.Serializable;
import java.net.URL;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
*
* @author WUJXIAO
*/
public class EhCacheUtil {
private static CacheManager manager;
static {
init();
}
public synchronized static void init() {
System.setProperty("net.sf.ehcache.enableShutdownHook","true");
URL url = EhCacheUtil.class.getResource("/ehcache.xml");
manager = new CacheManager(url);
}
public synchronized static void stop() {
if (manager != null) {
manager.shutdown();
manager = null;
}
}
private synchronized static Cache _GetCache(String cache_name,boolean autoCreate) {
Cache cache = manager.getCache(cache_name);
if (cache == null && autoCreate) {
manager.addCache(cache_name);
cache = manager.getCache(cache_name);
}
return cache;
}
/**
* 获取缓存中的数据
*
* @param name
* @param key
* @return
*/
public synchronized static Object get(String name,Serializable key) {
return get(Object.class,name,key);
}
/**
* 获取缓存中的数据
*
* @param <T>
* @param resultClass
* @param name
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public synchronized static <T> T get(Class<T> resultClass,String name,Serializable key) {
if (name != null && key != null) {
Cache cache = _GetCache(name,true);
Element element = cache.get(key);
if (element != null) {
T value = (T) element.getObjectValue();
cache.flush();
return value;
}
}
return null;
}
/**
* 写入缓存
*
* @param name
* @param key
* @param value
*/
public synchronized static void put(String name,Object key,Object value) {
put(name,(Serializable)key,(Serializable)value);
}
/**
* 写入缓存
*
* @param name
* @param key
* @param value
*/
public synchronized static void put(String name,Serializable key,Serializable value) {
if (name != null && key != null && value != null) {
Element element = new Element(key,value);
Cache cache = _GetCache(name,true);
cache.put(element);
cache.flush();
}
}
/**
* 清除缓冲中的某个数据
*
* @param name
* @param key
*/
public synchronized static void remove(String name,Serializable key) {
if (name != null && key != null) {
_GetCache(name,true).remove(key);
}
}
public synchronized static void clear(String name) {
_GetCache(name,true).removeAll();
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
