SSM-MyBatis-18:Mybatis中二级缓存和第三方Ehcache配置

简介:   ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------     二级缓存   Mybatis中,默认二级缓存是开启的。可以关闭。  一级缓存开启的。

 

 

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

 

 

二级缓存

  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(1);
        System.out.println(depts.getDeptName());
        session.close();

        System.out.println("===================我是高冷的分割线=====================");
        SqlSession session2= MyBatisUtils.getSession();

        IDeptDAO mapper2 = session2.getMapper(IDeptDAO.class);
        Dept depts2 = mapper2.findDeptnoALLEmpsMoreSql(1);
        System.out.println(depts2.getDeptName());
        session2.close();


    }

 

    运行结果

      

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

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

  二级缓存参数配置

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

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

 

    <!--
        eviction:清理缓存策咯,默认值LRU,最近最少使用先清除
        flushInterval:刷新间隔,默认不设置,就是永久
        size:对象,默认1024
        readOnly:只读,默认false
     -->
    <!--二级缓存-->
    <cache eviction="FIFO" flushInterval="60000" size="512" 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.4</version>
        </dependency>
        <!--MyBatis整合EhCache的包-->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.1.0</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="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        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 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 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="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

 

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

    运行结果

    看到这个表示成功

    Cache Hit Ratio  缓存命中率

 

 

 

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

 

目录
相关文章
|
5月前
|
XML Java 数据库连接
MyBatis的常见配置
MyBatis 常见配置包括数据库连接、类型别名、映射器等核心模块,合理配置可提升开发效率与系统性能。主要内容涵盖核心配置文件结构、关键配置项详解及配置优先级说明。
573 4
|
7月前
|
存储 缓存 NoSQL
mybatisplus一二级缓存
MyBatis-Plus 继承并优化了 MyBatis 的一级与二级缓存机制。一级缓存默认开启,作用于 SqlSession,适用于单次会话内的重复查询;二级缓存需手动开启,跨 SqlSession 共享,适合提升多用户并发性能。支持集成 Redis 等外部存储,增强缓存能力。
|
11月前
|
Oracle 关系型数据库 Java
【YashanDB知识库】Mybatis-Plus适配崖山配置
【YashanDB知识库】Mybatis-Plus适配崖山配置
|
6月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
414 18
|
11月前
|
Java 数据库连接 微服务
微服务——MyBatis配置——事务管理
本段内容主要介绍了事务管理的两种类型:JDBC 和 MANAGED。JDBC 类型直接利用数据源连接管理事务,依赖提交和回滚机制;而 MANAGED 类型则由容器全程管理事务生命周期,例如 JEE 应用服务器上下文,默认会关闭连接,但可根据需要设置 `closeConnection` 属性为 false 阻止关闭行为。此外,提到在使用 Spring + MyBatis 时,无需额外配置事务管理器,因为 Spring 模块自带的功能可覆盖上述配置,且这两种事务管理器类型均无需设置属性。
187 0
|
11月前
|
Java 数据库连接 数据库
微服务——MyBatis配置——多环境配置
在 MyBatis 中,多环境配置允许为不同数据库创建多个 SqlSessionFactory。通过传递环境参数给 SqlSessionFactoryBuilder,可指定使用哪种环境;若忽略,则加载默认环境。`environments` 元素定义环境配置,包括默认环境 ID、事务管理器和数据源类型等。每个环境需唯一标识,确保默认环境匹配其中之一。代码示例展示了如何构建工厂及配置 XML 结构。
184 0
|
9月前
|
缓存 Java 数据库连接
Mybatis一级缓存详解
Mybatis一级缓存为开发者提供跨数据库操作的一致性保证,有效减轻数据库负担,提高系统性能。在使用过程中,需要结合实际业务场景选择性地启用一级缓存,以充分发挥其优势。同时,开发者需注意其局限性,并做好事务和并发控制,以确保系统的稳定性和数据的一致性。
320 20
|
11月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1655 0
|
存储 Java 关系型数据库
ssm026校园美食交流系统(文档+源码)_kaic
本文介绍了基于Java语言和MySQL数据库的校园美食交流系统的设计与实现。该系统采用B/S架构和SSM框架,旨在提高校园美食信息管理的效率与便捷性。主要内容包括:系统的开发背景、目的及内容;对Java技术、MySQL数据库、B/S结构和SSM框架的介绍;系统分析部分涵盖可行性分析、性能分析和功能需求分析;最后详细描述了系统各功能模块的具体实现,如登录、管理员功能(美食分类管理、用户管理等)和前台首页功能。通过此系统,管理员可以高效管理美食信息,用户也能方便地获取和分享美食资讯,从而提升校园美食交流的管理水平和用户体验。
|
Java 数据库连接 Maven
手把手教你如何搭建SSM框架、图书商城系统案例
这篇文章是关于如何搭建SSM框架以及实现一个图书商城系统的详细教程,包括了项目的配置文件整合、依赖管理、项目结构和运行效果展示,并提供了GitHub源码链接。
手把手教你如何搭建SSM框架、图书商城系统案例