• mybatis缓存(缓存原理、自定义缓存)


    1、缓存

    (1)什么是缓存

    存储在内存中的临时数据,将用户经常查询的数据放在缓存(内存)中,用户再次查询数据的时候就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,能够提高查询效率,解决了高并发系统的性能问题

    (2)为什么使用缓存

    减少和数据库的交互次数,减少系统开销,提高系统效率

    (3)什么样的数据使用缓存

    经常查询并且不经常改变的数据

    (4)mybatis缓存

    mybatis包含一个非常强大的查询缓存特性,可以非常方便地定制和配置缓存,缓存可以极大地提高查询效率

    mybatis系统默认定义了两级缓存:一级缓存和二级缓存

    一级缓存:默认情况下只有一级缓存开启(SqlSession级别的缓存,也称为本地缓存)

    二级缓存:需要手动开启和配置,它是基于namespace级别的缓存

    为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存

    查看源码:org.apache.ibatis.cache.Cache;

    Cache接口:

    public interface Cache {
        String getId();
    
        void putObject(Object var1, Object var2);
    
        Object getObject(Object var1);
    
        Object removeObject(Object var1);
    
        void clear();
    
        int getSize();
    
        ReadWriteLock getReadWriteLock();
    }

    缓存策略:

    默认:LRU,移除最长时间不被使用的对象

    2、缓存原理

    (1)一级缓存与二级缓存

     第一次从数据库中查询,然后存在缓存中

    先去二级缓存中查看没有的话再去一级缓存中查看,缓存中没有的话再去数据库查询

    (2)一级缓存

    接口:

    public interface StudentMapper {
       Student queryStudentById(@Param("studentno") String studentno);
    }

    配置:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="pers.zhb.mapper.StudentMapper"><!--绑定一个dao接口-->
          <select id="queryStudentById" resultType="pers.zhb.pojo.Student">
              select * from student where studentno=#{studentno}
          </select>
    </mapper>

    测试:

    public class MyTest {
        @Test
        public void test(){
            SqlSession sqlSession= MybatisUtils.getSqlSession();
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            Student student1=studentMapper.queryStudentById("201811");
            System.out.println(student1);
            Student student2=studentMapper.queryStudentById("201811");
            System.out.println(student2);
        }
    }
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - Opening JDBC Connection
    DEBUG [main] - Created connection 439904756.
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201811(String)
    DEBUG [main] - <==      Total: 1
    Student(studentno=201811, sname=zhai, sex=男, birthday=1998-11-11, classno=80501, point=890, phone=1234567890, email=null)
    Student(studentno=201811, sname=zhai, sex=男, birthday=1998-11-11, classno=80501, point=890, phone=1234567890, email=null)

    两次查询只执行了一次SQL语句(第一次执行了SQL语句),第二次是直接在缓存中取得的数据

    (3)缓存失效

    查询不一样的数据:

        @Test
        public void test(){
            SqlSession sqlSession= MybatisUtils.getSqlSession();
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            Student student1=studentMapper.queryStudentById("201812");
            System.out.println(student1);
            Student student2=studentMapper.queryStudentById("201813");
            System.out.println(student2);
        }
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - Opening JDBC Connection
    DEBUG [main] - Created connection 439904756.
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    Student(studentno=201812, sname=zhai2, sex=男, birthday=1998-11-11, classno=80601, point=893, phone=19837372533, email=null)
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201813(String)
    DEBUG [main] - <==      Total: 1
    Student(studentno=201813, sname=zhai3, sex=男, birthday=1998-11-11, classno=80501, point=892, phone=19837372534, email=null)

    执行更新(增删改)操作:增删改操作可能会改变原来的数据,所以,必定会刷新缓存

    不执行更新操作:

      @Test
        public void test(){
            SqlSession sqlSession= MybatisUtils.getSqlSession();
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            Student student1=studentMapper.queryStudentById("201812");
            Student student2=studentMapper.queryStudentById("201812");
            System.out.println(student1==student2);
        }
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - Opening JDBC Connection
    DEBUG [main] - Created connection 171497379.
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    true

    只执行一次SQL语句,并且两次获取到的学生的对象为同一个对象

    在两次查询语句中插入一个更新操作:

     @Test
        public void test(){
            SqlSession sqlSession= MybatisUtils.getSqlSession();
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            Student student1=studentMapper.queryStudentById("201812");
    
            Student student=new Student();
            student.setStudentno("201813");
            student.setPhone("12345678912");
            studentMapper.UpdateStudent(student);
    
            Student student2=studentMapper.queryStudentById("201812");
            System.out.println(student1==student2);
        }
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - Opening JDBC Connection
    DEBUG [main] - Created connection 171497379.
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    DEBUG [main] - ==>  Preparing: update student set phone=? where studentno=? 
    DEBUG [main] - ==> Parameters: 12345678912(String), 201813(String)
    DEBUG [main] - <==    Updates: 1
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    false

    虽然查询的是同一个学生,但是此时缓存没有起作用(执行了两次查询操作),可以看出在插入了更新操作后,缓存失效

    通过不同的Mapper查询

    手动清理:

       @Test
        public void test(){
            SqlSession sqlSession= MybatisUtils.getSqlSession();
            StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
            Student student1=studentMapper.queryStudentById("201812");
            sqlSession.clearCache();
            Student student2=studentMapper.queryStudentById("201812");
            System.out.println(student1==student2);
        }
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
    DEBUG [main] - Opening JDBC Connection
    DEBUG [main] - Created connection 171497379.
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    DEBUG [main] - ==>  Preparing: select * from student where studentno=? 
    DEBUG [main] - ==> Parameters: 201812(String)
    DEBUG [main] - <==      Total: 1
    false

    一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接的这个区间段

    3、自定义缓存ehcache

    (1)导入依赖:

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

    (2)在mapper中指定使用自定义的缓存实现

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

    (3)缓存的配置文件:

    <?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 – 默认临时文件路径
         -->
        <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
        <!--
           defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
         -->
        <!--
          name:缓存名称。
          maxElementsInMemory:缓存最大数目
          maxElementsOnDisk:硬盘最大缓存个数。
          eternal:对象是否永久有效,一但设置了,timeout将不起作用。
          overflowToDisk:是否保存到磁盘,当系统当机时
          timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
          timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
          diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
          diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
          diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
          memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
          clearOnFlush:内存数量最大时是否清除。
          memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
          FIFO,first in first out,这个是大家最熟的,先进先出。
          LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
          LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
       -->
        <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"/>
    </ehcache>

    转载自:https://www.cnblogs.com/zqyanywn/p/10861103.html

    (4)引用缓存

  • 相关阅读:
    el表达式调用函数
    EL表达式
    mapReducer程序编写过程
    hadoop2.Xeclipse插件编译
    hadoop搭建与eclipse开发环境设置
    Sqoop-1.4.4工具import和export使用详解
    ZooKeeper典型应用场景一览
    hive原理和体系图解
    Linux中ssh免秘钥设置
    Annotation版本的HelloWorld
  • 原文地址:https://www.cnblogs.com/zhai1997/p/12795254.html
Copyright © 2020-2023  润新知