下面结合spring使用ehcache!
需要引入Ehcache和spring相关的jar包:
Ehcache配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="100000" eternal="false"
overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LFU" />
<!--这里设置了缓存失效时间10秒(timeToLiveSeconds)-->
<cache name="testCache" maxElementsInMemory="20000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LFU">
</cache>
</ehcache>
Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd" >
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
</beans>
使用:
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EhCacheSpringTest {
public static void main(String[] args) {
String ecacheName="testCache";
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
CacheManager cacheManager=(CacheManager)ctx.getBean("ehcacheManager");
Cache cache=cacheManager.getCache(ecacheName);
//存缓存
Element element=new Element(ecacheName, "Hello Cache33!");
cache.put(element);
//取缓存
Element el=cache.get(ecacheName);
String value=el.getObjectValue().toString();
System.out.println(value);
}
}
[源码下载]:(http://pan.baidu.com/s/1i5qTIAx)