EhCache 是一个纯Java的进程内缓存框架,是一种广泛使用的开源Java分布式缓存,具有快速、精干等特点,是Hibernate中默认的缓存提供者。不使用分布缓存,缓存的数据在各个服务器上单独存储,不方便系统开发。所以要使用分布式缓存对缓存数据进行集中管理。分布式缓存示意图如下:
mybatis提供二级缓存Cache接口,如下所示:
mybatis针对此接口提供了一个默认的实现类,如下所示:
虽然mybatis也实现提供了二级缓存,但是mybatis的特长是SQL操作,而不是缓存管理,比如实现分布式缓存,mybatis就不支持此功能。为了提高缓存的性能将mybatis与第三方的缓存数据库框架整合即可,如ehcache、redis、memcache等。
通过上图可以看出只要实现了mybatis的cache接口就可以实现mybatis的二级缓存数据。
mybatis整合ehcache三部曲:
根据实现mybatis的二级缓存的原理,整合ehcache只需要完成以下三步即可:
1、引入缓存的依赖包
2、在classpath下添加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">
<!--
磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
path:指定在硬盘上存储对象的路径
-->
<diskStore path="java.io.tmpdir" />
<!--
defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
eternal:代表对象是否永不过期
timeToIdleSeconds:最大的发呆时间
timeToLiveSeconds:最大的存活时间
overflowToDisk:是否允许对象被写入到磁盘
-->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<!--
cache:为指定名称的对象进行缓存的特殊配置
name:指定对象的完整名
-->
<cache name="com.zbaccp.entity.Person" maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
</ehcache>
3、开启ehcache缓存
在mapper.xml中开启二级缓存是通过添加cache元素,cache元素提供了一个type属性,此属性指定一个实现了mybatis的Cache接口的实现类。对于ehcache缓存框架,它提供了一个mybatis的Cache接口的实现类,只需要指向此类即可。
同样也可根据需求调整缓存参数:
<cache type="org.mybatis.caches.ehcache.EhcacheCache" >
<property name="timeToIdleSeconds" value="3600"/>
<property name="timeToLiveSeconds" value="3600"/>
<!-- 同ehcache参数maxElementsInMemory -->
<property name="maxEntriesLocalHeap" value="1000"/>
<!-- 同ehcache参数maxElementsOnDisk -->
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>