EhCache简单例子

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

public class EhCacheUtil {
	public static CacheManager cacheManager;
	private String cacheName;
	int maxElementsInMemory = 1000;
	static {
		if (cacheManager == null)
			try {
				cacheManager = CacheManager.create();
			} catch (CacheException ex) {
				ex.printStackTrace();
			}
	}

	/**
	 * 构造子
	 * @param cacheName
	 */
	public EhCacheUtil(String cacheName) {
		if (cacheName == null && "".equals(cacheName.trim()))
			throw new IllegalArgumentException("缓存名称不能为空!");
		this.cacheName = cacheName;
	}

	/**
	 * 获得缓存
	 * @param key
	 * @return
	 */
	public <T> T getCache(String key) {
		Cache cache = cacheManager.getCache(this.cacheName);
		if (cache != null) {
			Element element = cache.get(key);
			return (T) (element != null ? element.getValue() : null);
		}
		return null;
	}

	/**
	 * 添加缓存
	 * @param key
	 * @param value
	 */
	public void addCache(String key, Object value,int expires) {
		if (key != null && !"".equals(key)) {
			if(!cacheManager.cacheExists(this.cacheName))
				cacheManager.addCache(this.cacheName);
			Element element = new Element(key, value);
			element.setTimeToLive(expires);//设置失效时间(从创建到现在)
			cacheManager.getCache(this.cacheName).put(element);
		}
	}
	/**
	 * 更新缓存 TODO 待完善
	 * @param key
	 * @param newVal
	 */
	public void updateCache(){
		Cache cache = cacheManager.getCache(this.cacheName);
		if(cache!=null)
		  cache.flush();
	}
	/**
	 * 清空所有缓存
	 */
	public void clearAllCache(){
		cacheManager.clearAll();
	}
	/**
	 * 清空指定缓存
	 */
	public void clearCache(String key){
		addCache(key,null,1);
	}
}

 

 

你可能感兴趣的:(ehcache)