1. 程式人生 > >[MyBatis]Idea+maven第三方快取Ehcache框架整合

[MyBatis]Idea+maven第三方快取Ehcache框架整合

MyBaits畢竟是對資料庫操作的框架,對快取不大專業,所以留有對第三方快取框架整合的介面提供使用

新增依賴


    <!--Ehcache-->
    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.5</version>
    </dependency>






新增ehcache.xml(你寫錯檔名字,它就使用預設的mybaits自己的快取!不會生產資料夾,控制檯會提示:

代表它依舊用的是ehcache-failsafe裡的)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="D:\ehcache"/>

    <!-- 預設快取配置 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
    />


</ehcache>

關於引入xsd的url,可以

開啟settings->languages&frameworks->schemas and dtds ,新增地址 http://ehcache.org/ehcache.xsd

在需要配置的Mapper裡新增配置<property>可以不寫……


<mapper namespace="com.yiki.Dao.DepartmentMapper">

    <!--使用第三方快取框架

    -->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache">
        <property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
        <property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
        <property name="maxEntriesLocalHeap" value="1000"/>
        <property name="maxEntriesLocalDisk" value="10000000"/>
        <property name="memoryStoreEvictionPolicy" value="LRU"/>
    </cache>



測試生成快取代表成功

測試

 public void test8() throws IOException {
  start();


  System.out.println(d_mapper.getDeptById(1));
  System.out.println(d_mapper.getDeptById(1));
  System.out.println(d_mapper.getDeptById(1));

  sqlSession.close();
 }