------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

二级缓存

  Mybatis中,默认二级缓存是开启的。可以关闭。
  一级缓存开启的。可以被卸载吗?不可以的。一级缓存不可以卸载,天然和框架绑定。
内置二级缓存
    由于MyBatis从缓存中读取数据的依据与SQL的id相关,而非查询出的对象。所以,使用二级缓存的目的,不是在多个查询间共享查询结果(所有查询中只要查询结果中存在该对象,

    就直接从缓存中读取,这是对查询结果的共享,Hibernate中的缓存就是为了在多个查询间共享查询结果,但MyBatis不是),而是为了防止同一查询(相同的Sql id,相同的sql语句)的反复执行。

  一级缓存: 基于PerpetualCache 的 HashMap本地缓存,其生命周期为 Session,当 Session flush 或 close 之后,该Session中的所有 Cache 就将清空。

  二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap存储,不同在于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache

  对于缓存数据更新机制,当某一个作用域(一级缓存Session/二级缓存Namespaces)进行了 C/U/D 操作后,默认该作用域下所有 select 中的缓存将被clear

------------------------------------------------------------------------------------------------------------------------------------------------------------》

  内置二级缓存的使用简单配置步骤

      1.cacheEnabled=true;(这个默认值就是true,想用二级缓存可以不做配置,不想用改成false,在大配置中

<settings>
<setting name="cacheEnabled" value="true"/><!--开启,他也是默认值-->
<!--<setting name="cacheEnabled" value="false"/>--><!--关闭-->
</settings>

      2.实体类实现序列化接口Serializeble

        由于我做的是关联查询,并且没有做延迟加载,所以俩个实体类都得实现Serializeble接口

      3.在接口同名的xml小配置中

        加入一个自闭和的<cache/>


------------------------------------------------------------------------------------------------------------------------------------------------------------》

  内置二级缓存存在性证明

  都已经知道一级缓存是sqlsession的级别,如果要是close掉,换成不同的sqlsession怎么办?

/*二级缓存*/
@Test
public void t4SecondCacheHasExist(){
SqlSession session= MyBatisUtils.getSession(); IDeptDAO mapper = session.getMapper(IDeptDAO.class);
Dept depts = mapper.findDeptnoALLEmpsMoreSql();
System.out.println(depts.getDeptName());
session.close(); System.out.println("===================我是高冷的分割线=====================");
SqlSession session2= MyBatisUtils.getSession(); IDeptDAO mapper2 = session2.getMapper(IDeptDAO.class);
Dept depts2 = mapper2.findDeptnoALLEmpsMoreSql();
System.out.println(depts2.getDeptName());
session2.close(); }

    运行结果

      

  但由于他对数据库只发了上面的sql,分割线后就没有去数据库去查找了,而sqlsession关闭掉了,并且又开了一个,说明二级缓存真的存在,是真的运用上了

-----------------------------------------------------------------------------------》

  二级缓存参数配置

    在接口同名xml小配置中,可以指定具体的二级缓存参数配置

    我以代码加注释的方式来解释一波

    <!--
eviction:清理缓存策咯,默认值LRU,最近最少使用先清除
flushInterval:刷新间隔,默认不设置,就是永久
size:对象,默认1024
readOnly:只读,默认false
-->
<!--二级缓存-->
<cache eviction="FIFO" flushInterval="" size="" readOnly="true"/>
     eviction:清理缓存策咯,默认值LRU,最近最少使用先清除,此处设置的FIFO是先进先出的队列形式,先进来的先清除
flushInterval:刷新间隔,默认不设置,就是永久,单位毫秒
size:对象,默认1024
readOnly:只读,默认false

------------------------------------------------------------------------------------》

    二级缓存可以在一条sql语句上设置他的不开启-----------》局部关闭

    useCache改为false,不使用,不开启

    方法如下

    <!--设置二级缓存单条sql失效-->
<select id="findDeptnoALLEmpsMoreSql" resultMap="DeptMoreSqlMapper" useCache="false">
SELECT deptNo,deptName FROM dept WHERE deptNo=#{deptNo}
</select>

-------------------------------------------------------------------------------------》

第三方的二级缓存引用---ehcache

  使用方式

    1.引入jar包,我给你们提供节点

        <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.</version>
</dependency>
<!--MyBatis整合EhCache的包-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.</version>
</dependency>

    2.小配置中添加<cache/>具体配置,引用到第三方的缓存

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

    3.引入配置xml文件                       ehcache.xml                   名字一定这么取,别的不可以

      里面内容

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
its value in the running VM. The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/> <!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. -->
<defaultCache
maxElementsInMemory=""
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="true"
/> <!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts The following attributes are required for defaultCache: name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. --> <!-- Sample cache named sampleCache1
This cache contains a maximum in memory of elements, and will expire
an element if it is idle for more than minutes and lives for more than
minutes. If there are more than elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory=""
eternal="false"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="true"
/> <!-- Sample cache named sampleCache2
This cache contains elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory=""
eternal="true"
timeToIdleSeconds=""
timeToLiveSeconds=""
overflowToDisk="false"
/> --> <!-- Place configuration for your caches following --> </ehcache>

    接着我们调用刚才二级缓存存在性证明的那个方法,测试引用到了第三方框架ehcache了没

    运行结果

    看到这个表示成功

    Cache Hit Ratio  缓存命中率

--------------------------------孤傲的程序员------------------------------------------------------------------------------------------------

SSM-MyBatis-18:Mybatis中二级缓存和第三方Ehcache配置的更多相关文章

  1. Mybatis五(一级二级缓存、第三方缓存)

    一级缓存 Mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言.所以在参数和SQL完全一样的情况下,我们使用同一个SqlSess ...

  2. Mybatis整合Redis实现二级缓存

    Mybatis集成ehcache . 为什么需要缓存 拉高程序的性能 . 什么样的数据需要缓存 很少被修改或根本不改的数据 业务场景比如:耗时较高的统计分析sql.电话账单查询sql等 . ehcac ...

  3. mybatis(4)_二级缓存深入_使用第三方ehcache配置二级缓存

    增删改对二级缓存的影响 1.增删改也会清空二级缓存 2.对于二级缓存的清空实质上是对value清空为null,key依然存在,并非将Entry<k,v>删除 3.从DB中进行select查 ...

  4. mybatis 使用redis实现二级缓存(spring boot)

    mybatis 自定义redis做二级缓存 前言 如果关注功能实现,可以直接看功能实现部分 何时使用二级缓存 一个宗旨---不常变的稳定而常用的 一级是默认开启的sqlsession级别的. 只在单表 ...

  5. myBatis源码解析-二级缓存的实现方式

    1. 前言 前面近一个月去写自己的mybatis框架了,对mybatis源码分析止步不前,此文继续前面的文章.开始分析mybatis一,二级缓存的实现.附上自己的项目github地址:https:// ...

  6. MyBatis加强(1)~缓存机制(一级缓存、二级缓存、第三方缓存技术redis、ehcache)

    一.缓存机制 使用缓存可以使应用更快地获取数据,避免频繁的数据库交互操作,尤其是在查询越多,缓存命中率越高 的情况下,缓存的作用就越明显. 1.缓存原理:Map ■ 查询时,先从缓存区查询:找到,返回 ...

  7. Mybatis架构原理(二)-二级缓存源码剖析

    Mybatis架构原理(二)-二级缓存源码剖析 二级缓存构建在一级缓存之上,在收到查询请求时,Mybatis首先会查询二级缓存,若二级缓存没有命中,再去查询一级缓存,一级缓存没有,在查询数据库; 二级 ...

  8. 缓存架构中的服务详解!SpringBoot中二级缓存服务的实现

    创建缓存服务 创建缓存服务接口项目 创建myshop-service-redis-api项目,该项目只负责定义接口 创建项目的pom.xml: <?xml version="1.0&q ...

  9. Hibernatne 缓存中二级缓存简单介绍

    hibernate的session提供了一级缓存,每个session,对同一个id进行两次load,不会发送两条sql给数据库,但是session关闭的时候,一级缓存就失效了. 二级缓存是Sessio ...

随机推荐

  1. 50行代码实现的一个最简单的基于 DirectShow 的视频播放器

    本文介绍一个最简单的基于 DirectShow 的视频播放器.该播放器对于初学者来说是十分有用的,它包含了使用 DirectShow 播放视频所有必备的函数. 直接贴上代码,具体代码的含义都写在注释中 ...

  2. Linux - 延伸正则表达式

    RE 字符 意义与范例 + 意义:重复『一个或一个以上』的前一个 RE 字符 范例:搜寻 (god) (good) (goood)... 等等的字串. 那个 o+ 代表『一个以上的 o 』所以,底下的 ...

  3. obj-c在Xcode之外如何使用@import关键字

    在Xcode中@import可以很方便的代替#import的功能,具体区别和便利请自行google之. 这里简单介绍下在Xcode之外如何使用@import.直接以 @import Foundatio ...

  4. linux 常见命令及说明杂记

    systemctl 命令: systemctl 是管制服务的主要工具, 它整合了chkconfig 与 service功能于一体.示例:systemctl is-enabled iptables.se ...

  5. angularjs作用域之transclude

    transclude是一个可选的参数.如果设置了,其值必须为true,它的默认值是false.嵌入有时被认为是一个高级主题,但某些情况下它与我们刚刚学习过的作用域之间会有非常好的配合.使用嵌入也会很好 ...

  6. Python基本数据类型之列表、元组、字典、集合及其魔法

    列表 1.列表可存放任何东西,并且可修改 2.列表有序 3.列表支持索引与切片 4.支持for,while循环,所以列表为可迭代对象 5支持in操作,判断元素是否在列表中 6可多重索引嵌套列表 7.字 ...

  7. Day7 小练习(统计初始化数据的次数和对象之间的交互)

    写一个小练习,定义好一个类,每初始化一次,计数器+1,统计最后次数. class OldboyStudent: school = 'oldboy' count= def __init__(self,n ...

  8. BuautifulSoup4库详解

    1.BeautifulSoup4库简介 What is beautifulsoup ? 答:一个可以用来从HTML 和 XML中提取数据的网页解析库,支持多种解析器(代替正则的复杂用法) 2.安装 p ...

  9. MySQL中遇到的几种报错及其解决方法

    MySQL中遇到的几种报错及其解决方法 1.[Err] 1064 - You have an error in your SQL syntax; check the manual that corre ...

  10. Webpack vs Browersify vs SystemJs for SPAs

    https://engineering.velocityapp.com/webpack-vs-browersify-vs-systemjs-for-spas-95b349a41fa0 Right no ...