Getting started with mybatis | mybatis cache

Posted by scottgum on Tue, 25 Jan 2022 05:01:48 +0100

1 Introduction

  1. What is Cache?

    • There is temporary data in memory.
    • Put the data frequently queried by users in the cache (memory), and users do not need to query from the disk (relational database data file) but from the cache to query the data, so as to improve the query efficiency and solve the performance problem of high concurrency system.
  2. Why cache?

    • Reduce the number of interactions with the database, reduce system overhead and improve system efficiency.
  3. What kind of data can be cached?

    • Frequently queried and infrequently changed data.

2 Mybatis cache

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

  • Two levels of cache are defined by default in MyBatis system: L1 cache and L2 cache

    • By default, only L1 cache is on. (SqlSession level cache, also known as local cache)
    • L2 cache needs to be manually enabled and configured. It is based on namespace level cache.
    • In order to improve scalability, MyBatis defines the Cache interface Cache. We can customize the L2 Cache by implementing the Cache interface

3 L1 cache

The first level cache is also called the local cache.

  • Enabled by default.
  • SqlSession level cache.

When we execute the same query in the same session, we will not repeatedly read the sql, but from the cache.

3.1 four situations of L1 cache invalidation

  1. sqlSession is different

  2. The sqlSession is the same, but the query conditions are different

  3. sqlSession is the same. Add, delete and modify operations are performed between the two queries!

  4. sqlSession is the same. Manually clear the L1 cache.

    session.clearCache();//Manually clear cache
    

4 L2 cache

  • L2 cache is also called global cache. The scope of L1 cache is too low, so L2 cache was born

  • Based on the namespace level cache, a namespace corresponds to a L2 cache;

  • Working mechanism

    • When a session queries a piece of data, the data will be placed in the first level cache of the current session;

    • If the current session is closed, the L1 cache corresponding to the session is gone; But what we want is that the session is closed and the data in the L1 cache is saved to the L2 cache;

    • With the new session query information, you can get the content from the L2 cache.

    • The data found by different mapper s will be placed in their corresponding cache (map);

4.1 use of L2 cache

  1. mybatis-config.xml enable global cache

    <settings>
    	<setting name="cacheEnabled" value="true"/>
    </settings>
    
  2. Configure the cache in the namespace where you want to turn on the cache Official documents

    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
    #This more advanced configuration creates a FIFO cache, which is refreshed every 60 seconds. It can store up to 512 references of the result object or list, and the returned objects are considered read-only. Therefore, modifying them may conflict with callers in different threads.
    
  3. test

    @Test
        public void testQueryUserById(){
            SqlSession session = SqlSessionUtil.getSession();
            SqlSession session2 = SqlSessionUtil.getSession();
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            BlogMapper mapper2 = session2.getMapper(BlogMapper.class);
            Blog user = mapper.queryBlogById(1);
            System.out.println(user);
            session.close();
            Blog user2 = mapper2.queryBlogById(1);
            System.out.println(user2);
            System.out.println(user==user2);
            session2.close();
        }
    

Only after the session ends will the data be stored from the L1 cache to the L2 cache.

5 third party cache EhCache

  1. Import corresponding dependencies

    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>
    
  2. Open EhCache in the corresponding mapper configuration file.

    <cache type = "org.mybatis.caches.ehcache.EhcacheCache" />
    
  3. Create a new ehcache XML file

    <?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: Is the cache path, ehcache There are two levels: memory and disk. This attribute defines the cache location of the disk. The parameters are explained as follows:
        user.home – User home directory
        user.dir – User's 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"/>
    </ehcache>
    

For detailed parameter design, please refer to the official documents. ehcache official document

Topics: Java Database MySQL Mybatis