1. Introduction

  1. What is caching?
    • Temporary data exists in memory
    • The data frequently queried by users are stored in the cache (memory), so that users do not need to query from disk (relational database data file), but query from the cache, thus improving the query efficiency and solving the performance problem of high concurrency system
  2. Why cache?
    • Reduce the number of interactions with the database
  3. What kind of data can be cached?
    • Data that is frequently queried and infrequently changed

2. MyBatis cache

  • MyBatis includes a very powerful query caching feature, which makes it very easy to customize and configure the cache, which can greatly improve query efficiency
  • MyBatis defines two levels of caching by default:Level 1 cacheandThe second level cache
    • By default, only level 1 cache is enabled (SqlSession level cache, also known as local cache)
    • Level 2 caching, which needs to be manually enabled and configured, is namespace-level caching
    • In order to improve the scalability, MyBatis defines the Cache interface Cache, we can customize the secondary Cache by implementing the Cache interface

3. Level 1 cache

  • Level 1 caching is enabled by default

  • Level 1 cache is also called local cache:

    • Data retrieved during the same session with the database is stored in the local cache
    • In the future, if you want to retrieve the same data, you can just pull it from the cache instead of querying the database
  • Level 1 cache is SqlSession level cache, it is always on, we can not turn it off

  • Level-1 cache failure result: The same data needs to be queried again

  • There are four cases of level 1 cache failure:

    1. Different SQLSessions: Caches in each sqlSession are independent of each other

    2. The same sqlSession, different query conditions

    3. The sqlSession is the same. The add, delete, and change operations are performed between the two queries

    4. SqlSession, manually clear level 1 cache (using a list statement to clear the cache)

      session.clearCache();
      Copy the code
  • A level 1 cache is a map

4. Level 2 cache

  • Level 2 cache is also called global cache. Level 1 cache scope is too low, so level 2 cache is created

  • Based on namespace level caching, one namespace corresponds to one level 2 cache

  • Working mechanism:

    • A session queries a piece of data, and the data is placed in the level 1 cache for the current session. If the current session is closed, the level 1 cache for that session is gone. However, what we want is that the session is closed, the data in the level 1 cache is saved to the level 2 cache, and the new session can query the information from the level 2 cache, and the data detected by different Mapper will be hidden in its own cache (Map)
  • Procedure for enabling level 2 cache:

    1. Enable global cache mybatis-config.xml

      <setting name="cacheEnabled" value="true"/>
      Copy the code
    2. Go to each mapper.xml configuration using level 2 caching

      <cache/>Official example =====> View official documents<cache
        eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"/>
      <! This more advanced configuration creates a FIFO cache, refreshed every 60 seconds, that can store up to 512 references to result objects or lists, and the returned objects are considered read-only, so modifying them may conflict with callers in different threads. -->
      Copy the code
  • Conclusion:

    • As long as level 2 caching is enabled, our queries in the same Mapper can get data in level 2 cache
    • The detected data is placed in level 1 cache by default
    • Data in the level 1 cache is transferred to the level 2 cache only after the session is committed or closed

5. Caching principle

  • Cache schematic

6. EhCache

  • Third party cache implementation – EhCache

  • EhCache is a widely used Java story-sharing cache for general-purpose caches

  • Use EhCache in your application

    • Introduce dependent JAR packages

      <! -- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
      <dependency>
          <groupId>org.mybatis.caches</groupId>
          <artifactId>mybatis-ehcache</artifactId>
          <version>1.1.0</version>
      </dependency>
      Copy the code
    • Use the corresponding cache in the Mapper configuration file

      <mapper namespace = "Org. Acme. FooMapper" > 
          <cache type = "Org. Mybatis. Caches. Ehcache. EhcacheCache" /> 
      </mapper>
      Copy the code
    • Write the ehcache. XML file, and if the /ehcache. XML resource is not found or there is a problem when loading, the default configuration is used

      
                
      <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
               updateCheck="false">
          <! -- diskStore: indicates the cache path. Ehcache is divided into memory and disk levels. This attribute defines the cache location of the disk. The parameters are as follows: user.home - User home directory user.dir - User current working directory java.io. Tmpdir - Default temporary file path -->
          <diskStore path="./tmpdir/Tmp_EhCache"/>
      
          <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"/>
          <! DefaultCache: the defaultCache policy, which is used when ehcache cannot find the defined cache. Only one can be defined. -->
          <! -- name: indicates the cache name. MaxElementsInMemory: indicates the maximum number of caches. MaxElementsOnDisk: indicates the maximum number of caches on a hard disk. Eternal: Whether the object is permanent. Once it is set, timeout will not work. OverflowToDisk: whether to save to a disk when the system is down timeToIdleSeconds: Sets the time that the object is allowed to remain idle before becoming invalid (unit: second). Used only when eternal=false object is not permanently valid, optional property, default is 0, that is infinite idle time. TimeToLiveSeconds: Sets the time (in seconds) that the object is allowed to live before becoming invalid. The maximum time is between the creation time and the expiration time. Used only when eternal=false object is not permanently valid, the default is 0., that is, the object lifetime is infinite. DiskPersistent: Whether the disk store inside between restarts of the Virtual Machine. The default value is false. DiskSpoolBufferSizeMB: This parameter sets the size of the DiskStore cache. The default is 30MB. Each Cache should have its own buffer. DiskExpiryThreadIntervalSeconds: disk failure thread running time interval, the default is 120 seconds. MemoryStoreEvictionPolicy: when maxElementsInMemory limit is reached, Ehcache will be based on the specified strategies to clear the memory. The default policy is LRU (least recently used). You can set it to FIFO (First in, first out) or LFU (less used). ClearOnFlush: Specifies whether to flush the maximum memory. MemoryStoreEvictionPolicy: optional strategies are: the LRU (least recently used, the default policy), FIFO (first in first out), LFU (at least) visited. FIFO, first in first out, this is the most familiar one. LFU, Less Frequently Used, is the strategy Used in the above example. Frankly, it is the strategy that has been Used least. As mentioned above, cached elements have a hit attribute, and the one with the smallest hit value is cleared from the cache. The cached element has a timestamp. When the cache is full and space needs to be made for a new element, the element whose timestamp is furthest from the current time is removed from the cache. -->
      
      </ehcache>
      Copy the code