在Mybatis中使用自定義緩存ehcache

自定義緩存 - ehcache

Ehcache是一種普遍使用的開源Java分佈式緩存。主要面向通用緩存,Java EE和輕量級容器java

  1. 導包
<!-- 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>
  1. 在 Mapper.xml 中指定使用 ehcache 緩存實現
<!--在當前 Mapper.xml 中使用二級緩存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  1. 在resource中定義配置文件 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" updateCheck="false">

    <!--
    diskStore: 緩存路徑, ehcache分爲內存和磁盤兩級, 此屬性定義磁盤的緩存位置
    參數:
    user.home - 用戶主目錄
    user.dir - 用戶當前工做目錄
    java.io.tmpdir - 默認臨時文件路徑
    -->

    <!--當二級緩存的對象 超過內存限制時(緩存對象的個數>maxElementsInMemory),存放入的硬盤文件  -->
    <diskStore path="./tempdir/Tmp_Ehcache"/>

    <!--default 默認緩衝策略, 當ehcache找不到定義的緩存時, 則使用這個緩存策略, 這個只能定義一個-->
    <defaultCache
        eternal="false"
        maxElementsInMemory="10000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="259200"
        memoryStoreEvictionPolicy="LRU"/>
    
    <cache
        name="cloud_user"
        eternal="false"
        maxElementsInMemory="5000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LRU"/>

    <!--
       maxElementsInMemory:設置 在內存中緩存 對象的個數
       maxElementsOnDisk:設置 在硬盤中緩存 對象的個數
       eternal:設置緩存是否 永遠不過時
       overflowToDisk:當系統宕機的時候是否保存到磁盤上
       maxElementsInMemory的時候,是否轉移到硬盤中
       timeToIdleSeconds:當2次訪問 超過該值的時候,將緩存對象失效
       timeToLiveSeconds:一個緩存對象 最多存放的時間(生命週期)
       diskExpiryThreadIntervalSeconds:設置每隔多長時間,經過一個線程來清理硬盤中的緩存
       clearOnFlush: 內存數量最大時是否清除
       memoryStoreEvictionPolicy:當超過緩存對象的最大值時,處理的策略;LRU (最少使用),FIFO (先進先出), LFU (最少訪問次數)
     -->
</ehcache>
相關文章
相關標籤/搜索