package com.zhubaje.api.workflow.ehcache; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.springframework.beans.factory.DisposableBean; /** * 基本缓存支持类 <b>description:</b><br/> * <b>createtime:</b>2013-5-10 上午11:41:47<br/> * <b>remark:</b><br/> * * @version 1.0.0<br/> * */ @SuppressWarnings("unchecked") public class EhCacheBean<K extends Serializable, V> implements ICache<K, V>, DisposableBean { protected boolean useCache = true; protected CacheManager cacheManager; public CacheManager getCacheManager() { return cacheManager; } public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } protected Cache cache; @Override public void put(K k, V v) { if(useCache){ cache.put(new Element(k, v)); } } @Override public V get(K key) { if(!useCache){ return null; } if (!cache.isKeyInCache(key)) { return null; } return (V) cache.get(key).getObjectValue(); } @Override public List<K> keys() { return cache.getKeys(); } @Override public List<V> values() { List<K> keys = cache.getKeys(); List<V> result = new ArrayList<V>(keys.size()); for (Iterator<K> itKey = keys.iterator(); itKey.hasNext();) { result.add((V)cache.get(itKey.next()).getObjectValue()); } return result; } @Override public V remove(K key) { if (cache.isKeyInCache(key)) { Object obj = cache.get(key).getObjectValue(); cache.remove(key); return (V) obj; } return null; } public Cache getCache() { return cache; } public void setCache(Cache cache) { this.cache = cache; } @Override public void destroy() throws Exception { synchronized (cacheManager) { if (null != cacheManager) { cacheManager.shutdown(); } } } }