返回顶部

收藏

简单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 &amp;&amp; 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 &amp;&amp; key != null &amp;&amp; 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 &amp;&amp; key != null) {
            _GetCache(name, true).remove(key);
        }
    }

    public synchronized static void clear(String name) {
        _GetCache(name, true).removeAll();
    }

标签:java

收藏

0人收藏

支持

0

反对

0

发表评论