ehcache 缓存使用

 一:详细配置步骤

     1,添加ehcache.xml文件

      将ehcache.xml文件添加到src路径下面。ehcache.xml文件内容如下

<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文件中添加

    <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工具方法

     

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,测试

      

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


  • 9
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值