快两个月没来更新了,由于报考了SCJP就一直都忙于复习,还好过了。
今天写Ehcache。Ehcache是一套比较成熟的缓存解决方案,很多主流框架像Spring,Hibernate都对其有很好的支持。且 Ehcache是支持集群环境的,API也比较简单,上手比较容易。下面就介绍一下Ehcache主要功能的使用和在Spring环境下如何集成。
Ehcache默认的配置文件是ehcache.xml,内容如下:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
<!-- <diskStore path="c:\\mdcp_temp" />-->
<cacheManagerEventListenerFactory class="" properties="" />
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="600"
overflowToDisk="false"
>
</defaultCache>
<cache
name="configCache"
maxElementsInMemory="1000"
maxElementsOnDisk="1000"
eternal="true"
timeToIdleSeconds="300"
timeToLiveSeconds="1000"
overflowToDisk="false"
/>
</ehcache>
这里配置了一个名为configCache的缓存实例。参数说明如下:
name: 元素名称即缓存实例的名称。
maxElementsInMemory: 设定内存中保存对象的最大值。
overflowToDisk: 设置当内存中缓存到达maxElementsInMemory指定值时是否可以写到硬盘上。
eternal: 设置内存中的对象是否为永久驻留对象。如果是则无视timeToIdleSeconds和timeToLiveSeconds两个属性。
timeToIdleSeconds: 设置某个元素消亡前的停顿时间。指元素消亡之前,两次访问时间的最大时间间隔值。
timeToLiveSeconds: 设置某个元素消亡前的生存时间。指元素从构建到消亡的最大时间间隔。
注意:defaultCache不管用不用都是必须要配置的。
Java Code:
//初始化
CacheManager manager = new CacheManager(“src/config/ehcache.xml”);
//获取指定Cache对象
Cache configCache = manager.getCache(“configCache”);
//创建节点对象
Element element = new Element(“key1”,”value1”);
//保存节点到configCache
configCache.put(element);
//从configCache获取节点
Element element2 = configCache.getCache(“key1”);
Object value = element2.getValue();
//更新节点
configCache.put(new Element(“key1”,”value2”));
//删除节点
configCache.remove(“key1”);
以上是Ehcache的基本使用,是不是很简单?
下面介绍下在Spring环境下的配置。
首先需要一个jar文件:spring-modules-cache.jar。spring-module中包含了spring与其它框架的集成功能,除了cache外还有ant,jbpm,lucene,validation等。
Maven配置为:
<!-— Spring-modules-cache -->
<dependency>
<groupId>org.springmodules</groupId>
<artifactId>spring-modules-cache</artifactId>
<version>0.8</version>
</dependency>
<!-- Ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.6.2</version>
</dependency>
Spring, Spring-modules-cache 以及 Ehcache间的依赖关系如下:
首先Ehcache会依赖于其核心配置文件ehcache.xml, 而Spring也依赖于其配置文件application.xml。加入Spring-modules-cache.jar后就可以在application.xml中创建EhCacheManagerFactoryBean对象,这个类有一个属性configLocation用于指定ehcache的配置文件。这样依赖关系就变成了application.xml依赖于ehcache.xml了。Spring-modules-cache在两者间充当了一个“粘合剂”的作用。
接着是applicaion.xml中的配置:
<!-- load the ehcache config -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<!-- load the the configCache -->
<bean id="configCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager" />
</property>
<property name="cacheName">
<value>configCache</value>
</property>
</bean>
这样就可以通过Spring的IOC特性在需要用到configCache的类中进行注入。得到configCache后就能直接像之前那样操作cache对象了。
今天就写到这里,以后会继续更新Ehcache和Spring整合后利用AOP特性实现对于方法的缓存,以及在Hibernate中作为二级缓存的使用和它在集群环境中使用。