EhCache简述:
纯java的开源缓存框架,是Hibernate默认的CacheProvider;可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存;支持内存和磁盘的缓存。
springMVC+mybatis+ehcache详细配置:
1、整合需要的jar包
ehcache-core-2.4.4.jar
spring-context-support.jar
ehcache-spring-annotations-1.1.2.jar
mybatis-ehcache-1.0.0.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.2.jar
2、项目添加配置文件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">
<diskStore path="java.io.tmpdir" /><!-- java.io.tmpdir 指的是你系统的缓存目录 -->
<!-- 缓存位置可以是自定义的硬盘地址也可以是JVM默认使用的缓存地址 -->
<!--<diskStore path="d:\cache"/> -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="true" />
<!-- 配置自定义缓存 name:Cache的唯一标识
maxElementsInMemory:缓存中允许创建的最大对象数 。
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大 。
eternal:Element是否永久有效,一但设置了,timeout将不起作用,对象永不过期。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前, 两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效, 如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值, 这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。
diskPersistent:是否缓存虚拟机重启期数据。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒 。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区 。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用) 。
<cache name="cache" maxElementsInMemory="10000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LFU" />-->
</ehcache>
3、在Spring配置文件中,添加
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:conf/ehcache/ehcache.xml" />
</bean>
4、在对应的mapper.xml中,添加
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"></cache>
或
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" >
<property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
<property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
<property name="maxEntriesLocalHeap" value="1000"/>
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
参数配置不加也可以,都会有一个默认值,如果不要带日志可以把LogginEhcache改成EhcacheCache。
在mapper.xml这样设置了,默认是全部操作都会执行缓存策略,如果有某些sql不需要执行,可以把useCache设置为false。
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" useCache="false">