标签:
一:详细配置步骤
1,添加ehcache.xml文件
将ehcache.xml文件添加到src路径下面。ehcache.xml文件内容如下
[html] view plaincopyprint?
<ehcache>
<diskStore path="java.io.tempdir" />
<defaultCache maxElementsInMemory="1000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="ehcacheName" maxElementsInMemory="10000"
eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000"
overflowToDisk="true" />
</ehcache>
2,添加spring配置文件
在applicContext.xml文件中添加
[html] view plaincopyprint?
<bean id="cacheManagerFactory"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"></bean>
<!-- 声明cacheManager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="cacheManagerFactory" ></bean>
二:使用
1,定义EHCache工具方法
[java] view plaincopyprint?
public class EHCache {
private static final CacheManager cacheManager = new CacheManager();
private Cache cache;
public EHCacheService(){
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,测试
[java] view plaincopyprint?
public class Test{
EHCache ehCache = new EHCache();
public void Test(){
//测试将json对象存入缓存中
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
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://my.oschina.net/glenxu/blog/476414