9.Mybatis Cache

Reprinted: https: //blog.kuangstudy.com/index.php/archives/508/

A. Cache

1 Introduction

  1. What is the cache [Cache]?

    • There is a temporary data in memory.

    • Users often query the data in the cache (memory), users do not need to query data (relational database data files) from the disk query, the query from the cache to improve query efficiency, solve the problem of high-performance concurrent systems .

  2. Why use the cache?

    • Reduce the number of interactions and databases, reduce system overhead and increase system efficiency.

  3. What kind of data can use the cache?

    • Often query and infrequently changing data

2.Mybatis Cache

  • MyBatis has includes a powerful query caching feature which can very easily customize and configure the cache. Caching can greatly improve query efficiency.

  • MyBatis system defined by default two cache: a cache and secondary cache

    • By default, only the first-level cache is turned on. (SqlSession level cache, also known as a local cache)

    • The need to manually open and secondary cache configuration, he is based namespace level cache.

    • In order to improve the scalability, MyBatis defines the cache interface Cache. We can customize the interface to the secondary cache by implementing Cache

3. cache

  • Also known as a cache local cache:

    • At the same database queries during the session data will be placed in the local cache.

    • If you later need to obtain the same data, take directly from the cache, you must not go to query the database;

(1) build the project mybatis_cache

UserMapper.java Interface:

1  // The ID to query the user 
2 the User queryById (@Param ( "ID") int ID);

UserMapper.xml:

1 <select id="queryById" parameterType="_int" resultType="User">
2     select * from mybatis.user where id = #{id};
3 </select>

Test code:

 1 @Test
 2 public void queryByIdTest(){
 3     SqlSession session = MybatisUtils.getSession();
 4 
 5     UserMapper mapper = session.getMapper(UserMapper.class);
 6 
 7     User user = mapper.queryById(1);
 8     System.out.println(user);
 9 
10     System.out.println("=====================");
11 
12     User user2 = mapper.queryById(1);
13     System.out.println(user2);
14 
15     session.close();
16 }

View the log output:

Log analysis:

  • As can be seen from the log only once a query, the second query using the cache

(2) the case of cache miss (4 cases)

  1. The queries are different things

  2. CRUD operations that may change the original data, it is bound to refresh the cache!

  3. Query different Mapper.xml

  4. Manually clear the cache!

     1 @Test
     2 public void testQueryUserById(){
     3     SqlSession session = MybatisUtils.getSession();
     4     UserMapper mapper = session.getMapper(UserMapper.class);
     5 
     6     User user = mapper.queryUserById(1);
     7     System.out.println(user);
     8 
     9     session.clearCache();//手动清除缓存
    10 
    11     User user2 = mapper.queryUserById(1);
    12     System.out.println(user2);
    13 
    14     System.out.println(user==user2);
    15 
    16     session.close();
    17 }

     

(3) Summary

  • A cache enabled by default, only valid once SqlSession (  SqlSession MybatisUtils.getSession the session = ();   Session.close ();  the effective range)

4. The secondary cache

  • Secondary cache, also known as global cache, cache scope is too low, so the birth of the second-level cache

  • Based namespace level cache, a name space, corresponding to a secondary cache;

  • Working Mechanism

    • A session query a data, this data will be placed in a cache in the current session;

    • If the current session is closed, the corresponding session cache is gone; we want is, the session closed, the data is stored in the cache to the secondary cache ;

    • New session query information, you can get content from secondary cache;

    • Different mapper will on their own isolated data corresponding cache (Map); and

(1) Step:

  • Open global cache [mybatis-config.xml]

    <setting name="cacheEnabled" value="true"/>
  • Use: Each mapper.xml secondary cache configuration used, this configuration is very simple;] [xxxMapper.xml

    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> 
    或 <cache />

(2) Results: Use secondary cache

(3) issues:

  • When we directly use the  <cache />  without the need to implement serial interfaces entity class may be otherwise given configuration parameters

  • 所有的实体类先实现序列化接口 implements Serializable 

 1 import lombok.AllArgsConstructor;
 2 import lombok.Data;
 3 import lombok.NoArgsConstructor;
 4 
 5 import java.io.Serializable;
 6 
 7 @Data
 8 @AllArgsConstructor
 9 @NoArgsConstructor
10 public class User implements Serializable {
11     private int id;
12     private String name;
13     private String pwd;
14 
15 }

(4)小结:

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据

  • 查出的数据都会被默认先放在一级缓存中

  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

5.Mybatis缓存原理

查询顺序:二级缓存-->一级缓存-->数据库

6.自定义缓存Ehcache

(1)介绍:

  • Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

(2)使用:

  • 要在应用程序中使用Ehcache,需要引入依赖的jar包

    1 <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    2 <dependency>
    3     <groupId>org.mybatis.caches</groupId>
    4     <artifactId>mybatis-ehcache</artifactId>
    5     <version>1.1.0</version>
    6 </dependency>
  • 在mapper.xml中使用对应的缓存即可:

    1 <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
  • 编写ehcache的配置文件ehcache.xml:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3          xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
     4          updateCheck="false">
     5     <!--
     6        diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
     7        user.home – 用户主目录
     8        user.dir  – 用户当前工作目录
     9        java.io.tmpdir – 默认临时文件路径
    10      -->
    11     <diskStore path="./tmpdir/Tmp_EhCache"/>
    12     
    13     <defaultCache
    14             eternal="false"
    15             maxElementsInMemory="10000"
    16             overflowToDisk="false"
    17             diskPersistent="false"
    18             timeToIdleSeconds="1800"
    19             timeToLiveSeconds="259200"
    20             memoryStoreEvictionPolicy="LRU"/>
    21  
    22     <cache
    23             name="cloud_user"
    24             eternal="false"
    25             maxElementsInMemory="5000"
    26             overflowToDisk="false"
    27             diskPersistent="false"
    28             timeToIdleSeconds="1800"
    29             timeToLiveSeconds="1800"
    30             memoryStoreEvictionPolicy="LRU"/>
    31     <!--
    32        defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
    33      -->
    34     <!--
    35       name:缓存名称。
    36       maxElementsInMemory:缓存最大数目
    37       maxElementsOnDisk:硬盘最大缓存个数。
    38       eternal:对象是否永久有效,一但设置了,timeout将不起作用。
    39       overflowToDisk:是否保存到磁盘,当系统当机时
    40       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
    41       timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
    42       diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
    43       diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
    44       diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
    45       memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
    46       clearOnFlush:内存数量最大时是否清除。
    47       memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
    48       FIFO,first in first out,这个是大家最熟的,先进先出。
    49       LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
    50       LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
    51    -->
    52 
    53 </ehcache>

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12302037.html