MyBatis整合第三方缓存

        MyBatis缓存做的并不专业,用的是map,但是它给了我们一个接口Cache,我们通过实现这个接口,可以自定义缓存。本例子用的为ehcache ,Hibernate用的也是ehcache缓存技术。
        首先我们从官网上下载ehcache的jar包,还需要两个相关的jar。在MyBatis的基础上需要导入的jar包为 ehcache-core-2.6.8.jar  slf4j-api-1.6.1.jar 和 slf4j-log4j12-1.6.2.jar (请忽略版本号)。
        接下来我们需要写一个Cache的实现。但是MyBatis已经帮我们做好了,在MyBatis官网上有MyBatis和各种项目的整合。我们找到和ehcache的整合,如图:

点进去之后:查看文档

根据提示下载mybatis和ehcache整合所需要的jar包。如 mybatis-ehcache-1.0.3.jar    导入项目中。

接下来就是如何使用了,我们只需要在mapper.xml中指定一个Cache标签。

<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>
然后还需要在类路径下放一个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="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

第三方缓存整合总的来说 就三步:

  1、导入第三方jar包

  2、导入与第三方缓存整合的适配包,官方有。

  3、mapper.xml 中使用自定义缓存   

<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>
其他mapper.xml中如果也想使用 只需要引用已经使用的mapper.xml 的命名空间即可
如:
<mapper namespace="org.acme.AooMapper">
  <cache-ref namespace="org.acme.FooMapper" />
..
</mapper>
如果有什么问题欢迎讨论。大家一起进步!

posted @ 2017-08-24 00:54  西伯利亚狸  阅读(1385)  评论(0编辑  收藏  举报