org.springframework.cache.ehcache.EhCacheManagerFactoryBean
Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能。Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。
EhCache使用的场合
1.比较少更新表数据
EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等),Hibernate的二级缓存也都是这样;
2.对并发要求不是很严格的情况
多台中的缓存是不能实时同步的;
在介绍Spring的缓存配置之前,我们先看一下EHCache是如何配置.
applicationContext.xml
<import resource="spring-configuration/ehcache.xml" />
cache.xml
<bean id="defaultCacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="msnCache"
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="defaultCacheManager" />
</property>
<property name="cacheName">
<value>msnCache</value>
</property>
</bean>
EhCacheManagerFactoryBean:
缓存管理器,FactoryBean的公开了一个的EHCache的CacheManager单例,从指定的配置文件位置配置。 new出一个 CacheManager实例,Spring分别通过CacheManager.create()或new CacheManager()方式来创建一个ehcache基地.
EhCacheFactoryBean:创建缓存实例
===》ehcahe.xml《===
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect">
<diskStore path="java.io.tmpdir"/>
<!-- 定义默认的缓存区,如果在未指定缓存区时,默认使用该缓存区-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskSpoolBufferSizeMB="30"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<!-- 定义名字为"userCache"的缓存区-->
<cache name="userCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="300000"
timeToLiveSeconds="600000"
overflowToDisk="true"
/>
</ehcache>
说明:
缓存配置
name:缓存名称。
maxElementsInMemory:缓存中允许创建的最大对象数
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
总结
ehcache-spring的key生成策略
默认采用的是 HashCodeCacheKeyGenerator
基于方法参数的hashkey,类+方法名+参数hashCode