课时11:禁用、清理二级缓存,以及整合Ehcache缓存

.1)如何禁用二级缓存

  1 在具体要关闭的mapper.xml中的select标签里面填写

<select id="selectStudentById" resultType="student" parameterType="Integer" useCache="false">
        select * from student where stuno=#{stuno}
    </select>

.2).清理:与清理缓存一级缓存相同

 1 SqlSession.close()才会记录成缓存;(执行增删改会将缓存清除了;设计的原因 是为了脏数据的产生)在二级缓存中,SqlSession.commit()不能查询自身的commit()。

    SqlSession.commit()会清理一级缓存和二级缓存;但是清理二级缓存时不能查询自身的SqlSession.commit()

 2 在select标签中添加flushCache="true"也可以清除缓存

.3)命中率:

  1.zs:0%  ===>50%  ===> 66.6%  ===> 75%

.4)整合Ehcache二级缓存 (第三方缓存有很多种,以Ehcache为例)

  1.需要导入如下三个jar包

<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache-core</artifactId>
    <version>2.6.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

  2.编写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">
<!--    当二级缓存的对象  超过内存限制时 (缓存对象个数>maxElementsInMemory)当存入的硬盘文件-->
    <diskStore path="E:uEhcache"/>

<!--
    maxElementsInMemory:设置在内存中缓存 对象的个数
    maxElementsOnDisk:设置在硬盘中缓存 对象的个数
    overflowToDisk:设置缓存是否 永久不过期
    diskPersistent:当内存中缓存的对象个数 超过maxElementsInMemory的时候 是否转移到硬盘
    timeToIdleSeconds:当两次访问 超过该值的时候,将缓存对象失效
    timeToLiveSeconds:一个缓存对象,最多存放的时间(生命周期 )
    diskExpiryThreadIntervalSeconds:每隔多长时间  通过一个线程 来清理硬盘中的缓存
    memoryStoreEvictionPolicy:当缓存对象的最大值时  处理的策略:LRU 这个值是 删除最少使用
-->
    <defaultCache
            eternal="false"
            maxElementsOnDisk="1000000"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="100"
            timeToLiveSeconds="100"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

  3.启二级缓存 在主配置中

<!--        开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>

  4.在mapper编写cache标签

<!--    声明开启-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<!--    如果编写了下面的值  会覆盖全局配置的那个ehcache.xml-->
<!--    <property name="maxElementsInMemory" value="2000"/>-->
<!--    <property name="overflowToDisk" value="true"/>-->
</cache>

  5.测试与mybatis自带的二级缓存一样的

原文地址:https://www.cnblogs.com/thisHBZ/p/12458112.html