簡單Ehcahe封裝
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(); }
</pre>