---
title: "Ehcache缓存框架"
author: "z7swf"
date: "2008-03-25T14:51:15Z"
tags: [".net", "Cache", "Hibernate", "XML", "框架"]
slug: "ehcache"
draft: false
lastmod: "2008-03-25T14:51:15Z"
id: 175843
url: "https://kt8668.iteye.com/blog/175843"
---

地址：[http://ehcache.sourceforge.net/](http://ehcache.sourceforge.net/)

 

 

Kernel: ehcache.jar

 

 

Xml：ehcache.xml

 

```
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
	<diskStore path="c:\\temp" />
	<cacheManagerEventListenerFactory class="" properties="" />

	<!--
	Uncomment the following in a clustered configuration.
	-->

	<!--<cacheManagerPeerProviderFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
		properties="peerDiscovery=automatic,multicastGroupAddress=230.0.0.1,multicastGroupPort=4446,timeToLive=1"
		propertySeparator=","
	/>
	<cacheManagerPeerListenerFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
	/>-->

	<!--
	Hibernate will use the defaultCache unless custom configurations are defined
	below for individual domain objects, collection, queries, etc.
	-->

	<defaultCache
		maxElementsInMemory="10000"
		eternal="false"
        timeToIdleSeconds="600"
		overflowToDisk="true"
	>
		<!--<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
		<bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />-->
	</defaultCache>
	
	<!--
	The cache name is the same as the class name specified in your Hibernate
	mapping file.
	-->

	<cache
		name="sampleCache"
		maxElementsInMemory="5"
		maxElementsOnDisk="100" 
		eternal="false"
        timeToIdleSeconds="2" 
        timeToLiveSeconds="2"
		overflowToDisk="true"
	>
		<!--<cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
		<bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />-->
	</cache>
</ehcache>
```

 

以上ehcache.xml是ehcache的配置文件，并且存放在应用的classpath中。下面是对该XML文件中的一些元素及其属性的相关说明：

 

&lt;diskStore&gt;元素：指定一个文件目录，当EHCache把数据写到硬盘上时，将把数据写到这个文件目录下。

 

&lt;defaultCache&gt;元素：设定缓存的默认数据过期策略。

 

&lt;cache&gt;元素：设定具体的命名缓存的数据过期策略。

 

&lt;cache&gt;元素的属性

 

name：缓存名称。通常为缓存对象的类名（非严格标准）。

 

maxElementsInMemory：设置基于内存的缓存可存放对象的最大数目。

 

maxElementsOnDisk：设置基于硬盘的缓存可存放对象的最大数目。

 

eternal：如果为true，表示对象永远不会过期，此时会忽略timeToIdleSeconds和timeToLiveSeconds属性，默认为false;

 

timeToIdleSeconds： 设定允许对象处于空闲状态的最长时间，以秒为单位。当对象自从最近一次被访问后，如果处于空闲状态的时间超过了timeToIdleSeconds属性值，这个对象就会过期。当对象过期，EHCache将把它从缓存中清空。只有当eternal属性为false，该属性才有效。如果该属性值为0，则表示对象可以无限期地处于空闲状态。

 

timeToLiveSeconds：设定对象允许存在于缓存中的最长时间，以秒为单位。当对象自从被存放到缓存中后，如果处于缓存中的时间超过了 timeToLiveSeconds属性值，这个对象就会过期。当对象过期，EHCache将把它从缓存中清除。只有当eternal属性为false，该属性才有效。如果该属性值为0，则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性，才有意义。

 

overflowToDisk：如果为true,表示当基于内存的缓存中的对象数目达到了maxElementsInMemory界限后，会把益出的对象写到基于硬盘的缓存中。

 

使用：

```
CacheManager cacheManager = EhcachePlugIn.getCacheManager();
Cache cache = cacheManager.getCache("sampleCache");
```

 EhcachePlugIn可以自定义为任何工厂，作用是返回一个CacheManager实例。

 

```
cacheManager.getCache("sampleCache");
```

 参数为ehcache文件中&lt;cache&gt;元素的name属性。

 

引入ehcache.xml

```
URL url = getClass().getResource("/"+xmlPath);
cacheManager = new CacheManager(url);
```

 xmlPath为ehcache.xml在classpath下的具体路径。

 

对象的存储

```
CacheManager cacheManager = EhcachePlugIn.getCacheManager();
Cache cache = cacheManager.getCache("sampleCache");
System.out.println("The Key In Cache?:"+cache.isKeyInCache(EHCACHE_KEY));
System.out.println("Cache is :"+cache);
		
		Element result = cache.get(EHCACHE_KEY);
		
		if(null==result)
		{
			System.out.println("No Data In Ehcache");
			List list = new ArrayList();
			
			for(int i=20;i<50;i++)
			{
				Student student = new Student(26,"kook"+i);
				list.add(student);
			}
			cache.put(new Element(EHCACHE_KEY,list));
			cache.flush();
			
			result = cache.get(EHCACHE_KEY);
		}

		List ehcacheList = (List)result.getValue();
		
		Iterator iter =  ehcacheList.iterator();
		
		while (iter.hasNext()) {
			Student element = (Student) iter.next();
			System.out.println("Studeng name is:"+element.getName());
		}
```

 

注意：如果缓存的对象要写入到硬盘中的话，则该对象必须实现了Serializable接口才行。

 

详细代码在附件中，为一个完成的ECLIPSE PROJECT.