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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值