系统为了提高并发性能,一般对系统进行了分布式部署(集群部署方式)
如果不是用分布式缓存,缓存数据在各个服务器单独存储,如果可发访问了多个服务器,那么每个服务器之间都会存在一个同样的缓存,不利于管理,
处理办法:将缓存放到一个单独的服务器进行管理,这里就用到了 缓存框架(redis memacahed ehcache)
MyBatis 的提供了支持 集成缓存的接口,下面我们,就以ehcahe为例,学习如何整合 缓存框架.
1、加入 mybatis-ehcache 整合包 和 ehcache 核心包。
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
2、在mapper.xml 中配置 <cache/>
<!-- 该类用 ehcache 实现了mybatis org.apache.ibatis.cache.Cache 接口 完成了 mybatis和ehcache直接的适配工作-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
如果不填写,那么默认配置 mybatis 的缓存实现类 PerpetualCache。(上一章二级缓存中我们已经进行了测试)
这里给他指定mybatis-ehcache适配包中的实现类:type=”org.mybatis.caches.ehcache.EhcacheCache”
3、在项目classpath 目录下添加 ehcache.xml 配置文件 内容如下
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="F:\ehcache"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
使用场景: 查询本月账单,这次对时时性要求不高的统计就可以使用缓存技术。
好了大功告成。现在就完成了所有整合。
这里仍然存在一个问题,就是缓存一旦 commit就会被清空,如果数据只是被修改了一点点,就清空了大了数据,也会存在效率的下降,这里就涉及到了 更生一层的 三级缓存 细粒度缓存,需要更加业务,工程师自己去编写。