EhCacheUtil.java 1.52 KB
package com.cjs.cms.util.cache;

import java.io.InputStream;

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

/**
 * EhCache
 * 
 * @author tongyufu
 *
 */
public class EhCacheUtil {

    public static Cache cache;

    static {
        InputStream stream = EhCacheUtil.class.getResourceAsStream("/ehcache.xml");
        CacheManager cacheManager = CacheManager.create(stream);
        cache = cacheManager.getCache("commonCache");
    }

    public static Object get(Object key) {
        Element value = cache.get(key);
        if (value == null) {
            return null;
        }
        return value.getValue();
    }

    public static void put(Object key, Object value) {
        cache.put(new Element(key, value));
    }

    /**
     * 保存缓存值
     * @param timeToIdleSeconds 设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
     * @param timeToLiveSeconds 设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大
     */
    public static void put(Object key, Object value, Integer timeToIdleSeconds,
                           Integer timeToLiveSeconds) {
        cache.put(new Element(key, value, false, timeToIdleSeconds, timeToLiveSeconds));
    }

    public static boolean remove(Object key) {
        return cache.remove(key);
    }

}