简单Ehcahe封装

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

 
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();
    }