环境搭建
将ehcache-2.1.0-distribution.tar.gz解压
需要将它们放置到WEB-INF/lib 下。
有一个重要的配置文件ehcache.xml,可以从ehcache 组件包中拷贝一个,也可以自
己建立一个。需要放到classpath 下。常放的路径为/WEB-INF/classes/ehcache.xml
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=manual, rmiUrls=//127.0.0.1:57651/paramCache" /> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=127.0.0.1,port=57651,socketTimeoutMillis=120000" /> <defaultCache maxElementsInMemory="10000" eternal="true" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" /> </defaultCache> <cache name="paramCache" maxElementsInMemory="10000" eternal="true" timeToIdleSeconds="100000" timeToLiveSeconds="100000" overflowToDisk="true"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" /> </cache> </ehcache>
应用类
package com.erayt.subfunds.cache; import java.io.Serializable; import org.apache.log4j.Logger; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class GlobalCache { private Logger logger = Logger.getLogger(GlobalCache.class); private CacheManager cacheManager ; private static Cache paramCache = null; public GlobalCache(){ init(); } public void init(){ if(cacheManager == null){ logger.info("初始化CacheManager"); cacheManager = CacheManager.create(this.getClass().getClassLoader().getResource("ehcache.xml")); } if(paramCache == null){ paramCache = cacheManager.getCache("paramCache"); } } public void putParam(String key, Serializable obj) { paramCache.put(new Element(key, obj)); } public void putParam(String key, Serializable obj, int liveTime) { paramCache.put(new Element(key, obj, false, liveTime, liveTime)); } public Object getParam(String key) { Element ele = paramCache.get(key); return ele == null ? null : ele.getObjectValue(); } public boolean removeParam(String key) { return paramCache.remove(key); } public void shutdown() { try{ if(paramCache!=null){ paramCache.dispose(); } }catch(Exception e){ e.printStackTrace(); } if(cacheManager!=null){ cacheManager.shutdown(); } } public void destroy() { shutdown(); } }