Mybatis引入第三方缓存库ehcache

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38409944/article/details/82493545

前言:

mybatis知道自己缓存做的不好 就暴露接口出来给别人做
Cache接口实现两个方法

putObject
getObject

所以我们可以引入第三方缓存库
这里我就介绍下ehcache
git下载地址:

git:https://github.com/mybatis/ehcache-cache

看看ehcache的类

 EhcacheCache extends AbstractEhcacheCache
 public abstract class AbstractEhcacheCache implements Cache

可以看出 是继承了 mybatis暴露的接口。
具体的配置 可以查看这个文档。

http://www.mybatis.org/ehcache-cache/

第一步 导入需要的四个jar包:
导入第三方缓存包:

ehcache-core-2.6.8.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.2.jar

导入与第三方缓存整合的适配包;官方有(https://github.com/mybatis);

mybatis-ehcache-1.0.3.jar  

指定Mapper添加cache使用二级缓存

<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

还要在conf下创建一个ehcache.xml: 注意 如果没有 则采用默认值

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 <!-- 磁盘保存路径 -->
 <diskStore path="D:\44\ehcache" />
 <defaultCache 
   maxElementsInMemory="10000" 
   maxElementsOnDisk="10000000"
   eternal="false" 
   overflowToDisk="true" 
   timeToIdleSeconds="120"
   timeToLiveSeconds="120" 
   diskExpiryThreadIntervalSeconds="120"
   memoryStoreEvictionPolicy="LRU">
 </defaultCache>
</ehcache>
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略

以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目 
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上

以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
 diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)

如果其他空间也想用这个缓存机制的话 不用重新写
只要引用那个使用了缓存的空间即可:

<cache-ref namespace="com.atguigu.mybatis.dao.EmployeeMapper"/>

猜你喜欢

转载自blog.csdn.net/qq_38409944/article/details/82493545