1.概述
三方提供的二级缓存有:ehcache、memcache
要想整合三方提供的二级缓存 (或者自定义二级缓存),必须实现org.apache.ibatis.cache.Cache接口,该接口的默认实现类是PerpetualCache
2.整合Ehcache二级缓存
(1)jar
ehcache-core.jar
mybatis-Ehcache.jar
slf4j-api.jar
(2)配置文件Ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!--当二级缓存的对象超过内存限制时(缓存对象的个数>maxElementsInMemory),存放入的硬盘文件 -->
<diskStore path="D:\Ehcache"/>
<!--
maxElementsInMemory:设置在内存中缓存对象的个数
maxElementsOnDisk:设置在硬盘中缓存对象的个数
eternal:设置缓存是否永远不过期
overflowToDisk:当内存中缓存的对象个数超过maxElementsInMemory的时候,是否转移到硬盘中
timeToIdleSeconds:当2次访问超过该值的时候,将缓存对象失效
timeToLiveSeconds:一个缓存对象最多存放的时间(生命周期)
diskExpiryThreadIntervalSeconds:设置每隔多长时间,通过一个线程来清理硬盘中的缓存
memoryStoreEvictionPolicy:当超过缓存对象的最大值时,处理的策略;LRU,FIFO,LFU
-->
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="1000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="100"
timeToLiveSeconds="100"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
(3)studentMapper.xml
开启Ehcache二级缓存
通过property覆盖Ehcache.xml中的值
<!-- 声明此namespace开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="maxElementsInMemory" value="2000"/>
</cache>