Spring之Ehcache整合

一、简介

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。Ehcache是一种广泛使用的开 源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。

二、引入Jar包

三 、配置文件ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
    <diskStore path="java.io.tmpdir"/>

    <!-- 设定缓存的默认数据过期策略 -->
    <defaultCache
            maxElementsInMemory="10000" 
            eternal="false" 
            overflowToDisk="true"
            timeToIdleSeconds="10"
            timeToLiveSeconds="20"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <cache name="myCache" 
        maxElementsInMemory="1000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="10"
        timeToLiveSeconds="20"/>

</ehcache>

name:缓存名称

maxElementsInMemory:内存中最大缓存对象数

maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大

eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false

overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行

diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。

maxElementsOnDisk:硬盘最大缓存个数。 

diskPersistent:是否缓存虚拟机重启数据 

diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 

memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。可以设置为FIFO(先进先出)或是LFU(较少使用)。 

clearOnFlush:内存数量最大时是否清除。 

四、Spring.xml配置文件引入缓存

   <!-- 开启注解,该注解一定要声明在spring主配置文件中才会生效 -->
    <cache:annotation-driven cache-manager="ehcacheManager"/>
    
    <!-- cacheManager工厂类,指定ehcache.xml的位置 -->
    <bean id="ehcacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
         <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>
    <!-- 声明cacheManager -->
    <bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
         <property name="cacheManager" ref="ehcacheManagerFactory" />
    </bean>

 五、使用注解实现缓存

@Cacheable、@CachePut、@CacheEvict

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/85634301