mybatis有自己的一级缓存和二级缓存,而实际项目中通常会用专门的缓存框架来进行缓存管理。EhCache是一个纯粹的Java进程内的缓存框架,缓存数据可以放内存和磁盘,具有快速、精干等特点。
这里,我们不谈ehcache的各种特点,通过一个简单demo来演示下mybatis与ehcache集合过程。为了演示方便,沿用Mybatis一级缓存与二级缓存的工程,继续在该工程上进行改造。
1、添加ehcache依赖
<!-- ehcache依赖 -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
2、配置Ehcache
在src/main/resources目录下新增ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<!-- 指定数据在磁盘中的存储位置 -->
<diskStore path="D:\DEV_ENV\ehcache" />
<!-- 缓存策略 -->
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
其中
- maxElementsInMemory:内存中最大缓存对象数
- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大
- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false
- overflowToDisk:true表示当内存缓存的对象数目达到了
- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒
- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性 值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限 期地处于空闲状态
- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EhCache将把它从缓存中清除。只有当eternal属性为false,该属性才有 效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有 意义
- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
3、修改UserMapper.xml文件
替代UserMapper.xml里面的二级缓存开关标签
<!-- ehcache配置项 -->
<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>
有部分属性在ehcache.xml里面配置过,则mapper文件中的属性会覆盖掉ehcache.xml里面的属性值。同样,也可以使用一种偷懒的方式,直接使用一行,这里其余的属性则都使用ehcache.xml里面的默认属性了。
<!-- ehcache配置项 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
改动点就上面三处,测试方法与之前相同,这里就不再赘述了,可以参考上一篇博文的测试方法。
以上,ehcache与mybatis结合最简单的示例了。