一:详细配置步骤
1,添加ehcache.xml文件
将ehcache.xml文件添加到src路径下面。ehcache.xml文件内容如下
< ehcache > < diskStore path = "java.io.tempdir" /> < defaultCache maxElementsInMemory = "1000" eternal= "false" timeToIdleSeconds = "86400" timeToLiveSeconds = "86400" overflowToDisk = "true" /> < cache name = "ehcacheName" maxElementsInMemory = "10000" eternal = "false" timeToIdleSeconds = "300000" timeToLiveSeconds = "600000" overflowToDisk = "true" /> </ ehcache >
2,添加spring配置文件
在applicContext.xml文件中添加
< bean id = "cacheManagerFactory" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation = "classpath:ehcache.xml" > </ bean > < bean id = "cacheManager" class = "org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref = "cacheManagerFactory" > </ bean >
二:使用
1,定义EHCache工具方法
public class EHCache { private static final CacheManager cacheManager = new CacheManager(); private Cache cache; public EHCache(){ this .cache=cacheManager.getCache( "ehcacheName" ) } public Cache getCache() { return cache; } public void setCache(Cache cache) { this .cache = cache; } public Object getCacheElement(String cacheKey) throws Exception { net.sf.ehcache.Element e = cache.get(cacheKey); if (e == null ) { return null ; } return e.getValue(); } public void addToCache(String cacheKey, Object result) throws Exception { Element element = new Element(cacheKey, result); cache.put(element); } }
2,测试
public class Test{ EHCache ehCache = new EHCache(); public void Test(){ JSONObject obj = new JSONObject(); obj.put("name" , "lsz" ); ehCache.addToCache("cache_json" ,obj); JSONObject getobj = (JSONObject)ehCache.getCacheElement("cache_json" ); System.out.println(getobj.toString()); } }
三:问题解决
1,框架环境是自己搭建的,添加ehcache后运行出错:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/cache] Offending resource: class path resource [applicationContext.xml]
出现这种问题,原因是因为在applicationContext.xml文件中 多加了
<cache:annotation-driven cache-manager="cacheManager" /> 将其去掉即可
2,框架需要添加jar包
spring-context-support-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar