本文参考网上多篇文章整合。
1.需要的jar包
ehcache-core-2.5.2.jar
slf4j-api-1.6.1.jar
cglib-2.2.jar [----这个包可能是不需要的]
ehcache-spring-annotations-1.1.2.jar
aopalliance.jar
2.在spring的配置文件applicationContext.xml中配置ehcache
<ehcache:annotation-driven cache-manager="ehCacheManager" />
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:conf/<span style="color:#ff0000;">ehcache.xml</span>" />
</bean>
3.ehcache.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messageCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
<cache name="messagesCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
至此,ehcache的配置完成。
使用demo进行测试
import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public abstract class Ehcache_Demo {
/**
* @param args
*/
//static CacheManager manager= new CacheManager();
/**
*##############################################################################
*
* @DESCRIBE
* @param args
* @throws InterruptedException
*
*##############################################################################
*/
public static void main(String[] args) throws InterruptedException {
CacheManager manager = new CacheManager("resource/conf/ehcache.xml");
String[] cacheNames = manager.getCacheNames();
System.out.println(System.getProperty("java.io.tmpdir"));
System.out.println("读取的缓存列表为:");
for(int i=0;i<cacheNames.length;i++){
System.out.println("-- "+(i+1)+" "+cacheNames[i]);
}
Cache cache = manager.getCache("messageCache");
Element element = new Element("key1", "value1");
cache.put(element);
element = cache.get("key1");
Serializable value = element.getValue();
System.out.println("序列化后的值为:"+value.toString());
element = cache.get("key1");
Object value1 = element.getObjectValue();
System.out.println("未序列化的值为:"+value1.toString());
int elementsInMemory = cache.getSize();
System.out.println("得到缓存的对象数量:"+elementsInMemory);
long elementsInMemory1 = cache.getMemoryStoreSize();
System.out.println("得到缓存对象占用内存的数量:"+elementsInMemory1);
long elementsInMemory2 = cache.getDiskStoreSize();
System.out.println("得到缓存对对象占用磁盘的数量:"+elementsInMemory2);
}
}
输出结果:
C:\Users\ADMINI~1\AppData\Local\Temp\
读取的缓存列表为:
-- 1 messageCache
-- 2 messagesCache
序列化后的值为:value1
未序列化的值为:value1
得到缓存的对象数量:1
得到缓存对象占用内存的数量:1
得到缓存对对象占用磁盘的数量:0