[MyBatis] Learning Minutes Seven: Cache (1)

words written in front

Cache is not necessary for the database, but for the system, the cache is indispensable. I didn't learn cache in the previous development, and I didn't use it, so this time I learn MyBatis, come and learn it seriously. If you are like me, then come and learn with me.

I'm going to tell you this. First of all, let's understand the general situation of the cache. If there is a cache, what is the order of the query, and then look at the first-level cache and the second-level cache in detail. Finally, we will discuss some details.

Of course, since it is learning, you should have a deeper understanding, so in the following pages, let's learn about the design of the cache interface, hibernate's cache, and then integrate Ehcache. In this section, I mainly study the design of the interface. What you want to learn depends on your own needs.

Overview

S80502-202454.jpg

1. When querying, first query the second-level cache. If the second-level cache is not available, go to the first-level cache. If there is no second-level cache, then query the database.

2. The data queried through the database is first cached in sessionthe , and then the data Mapperis cached again according to the data.

3. For caching, MyBatis provides an Cacheinterface. Obviously, we can also learn this design pattern.

L1 cache

The first-level cache, in simple terms, means that before the session is closed and cleared, if there is no addition, deletion or modification operation, and if the query conditions have not changed, the database will not be queried.

1. The session is not closed

2. The session is not empty

3. There is no addition, deletion or modification between queries

4. The query conditions have not changed

L2 cache

The second level cache should be the core content we use, but I don't know how to talk about this, but we will spend a lot of time on code demonstration caching later.

Let's see what MyBatis says about caching:

MyBatis includes a powerful transactional query caching feature which is very configurable and customizable. A lot of changes have been made in the MyBatis 3 cache implementation to make it both more powerful and far easier to configure.

By default, just local session caching is enabled that is used solely to cache data for the duration of a session. To enable a global second level of caching you simply need to add one line to your SQL Mapping file:

<cache/>

Literally that's it. The effect of this one simple statement is as follows:

All results from select statements in the mapped statement file will be cached. All insert, update and delete statements in the mapped statement file will flush the cache. The cache will use a Least Recently Used (LRU) algorithm for eviction. The cache will not flush on any sort of time based schedule (i.e. no Flush Interval). The cache will store 1024 references to lists or objects (whatever the query method returns). The cache will be treated as a read/write cache, meaning objects retrieved are not shared and can be safely modified by the caller, without interfering with other potential modifications by other callers or threads.

NOTEThe cache will only apply to statements declared in the mapping file where the cache tag is located. If you are using the Java API in conjunction with the XML mapping files, then statements declared in the companion interface will not be cached by default. You will need to refer to the cache region using the @CacheNamespaceRef annotation.

For ease of reading, the translation is as follows:

MyBatis includes a very powerful query caching feature that can be configured and customized very easily. Many improvements to the cache implementation in MyBatis 3 have been implemented, making it more powerful and easier to configure.

By default, caching is not enabled, except for local session caching, which enhances monetization and is necessary to handle circular dependencies. To enable L2 cache, you need to add a line to your SQL mapping file:

<cache/> literally does just that. The effect of this simple statement is as follows:

All select statements in the map statement file will be cached. All insert, update and delete statements in the map statement file flush the cache. The cache will be reclaimed using the Least Recently Used (LRU, least recently used) algorithm. According to the schedule (eg no Flush Interval, no flush interval), the cache will not be flushed in any chronological order. The cache stores 1024 references to list collections or objects (whatever the query method returns). The cache is treated as a read/write cache, meaning that object retrievals are not shared and can be safely modified by the caller without interfering with potential modifications made by other callers or threads.

理解

1. MyBatis supports caching

2. MyBatis needs to be <cache/>enabled . Note the word default .

3. After adding, deleting and modifying, the cache will be cleared.

4. The default caching mechanism is through LRU(Least Recently Used, least recently used).

5. The cache is readable and writable by default, which is safe, but it needs to be serialized and deserialized, so it takes time, which is very slow compared to inoperable. In other words, this is not Safe, leaving ownership in the hands of the user.

二级缓存属性及设置

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>
  • Configuration: userCache=false

  • <select ... useCache="false">

  • Additions, deletions and changes, the first/second level cache is emptied

<inset flushCache="true">

select tag: flushCache is false by default. If it is changed to true, the cache will be cleared after each query

  • sqlSession:clearCache() only clears the first level cache

  • localCacheScope local cache scope, SESSION|STATEMENT (level 1 cache can be disabled)

Finally, let's take a look at the detailed explanation of the MyBatis official website:

This more advanced configuration creates a FIFO cache that flushes once every 60 seconds, stores up to 512 references to result objects or lists, and objects returned are considered read-only, thus modifying them could cause conflicts between callers in different threads.

The available eviction policies available are:

LRU – Least Recently Used: Removes objects that haven't been used for the longst period of time. FIFO – First In First Out: Removes objects in the order that they entered the cache. SOFT – Soft Reference: Removes objects based on the garbage collector state and the rules of Soft References. WEAK – Weak Reference: More aggressively removes objects based on the garbage collector state and rules of Weak References. The default is LRU.

The flushInterval can be set to any positive integer and should represent a reasonable amount of time specified in milliseconds. The default is not set, thus no flush interval is used and the cache is only flushed by calls to statements.

The size can be set to any positive integer, keep in mind the size of the objects your caching and the available memory resources of your environment. The default is 1024.

The readOnly attribute can be set to true or false. A read-only cache will return the same instance of the cached object to all callers. Thus such objects should not be modified. This offers a significant performance advantage though. A read-write cache will return a copy (via serialization) of the cached object. This is slower, but safer, and thus the default is false.

NOTE Second level cache is transactional. That means that it is updated when a SqlSession finishes with commit or when it finishes with rollback but no inserts/deletes/updates with flushCache=true where executed.

翻译如下

This more advanced configuration creates a FIFO buffer that is flushed every 60 seconds, holding 512 references to the result object or list, and the returned object is considered read-only, so between callers in different threads Modifying them will cause conflicts.

Available retraction strategies are:

LRU - Least Recently Used: Removes objects that have not been used for the longest time. FIFO - First In First Out: Remove objects in the order in which they entered the cache. SOFT - Soft Reference: Remove objects based on garbage collector state and soft reference rules. WEAK - Weak References: More aggressive removal of objects based on garbage collector state and weak reference rules. The default is LRU.

flushInterval can be set to any positive integer, and they represent a reasonable time period in milliseconds. The default is not set, that is, there is no refresh interval, the cache is only refreshed when the statement is called.

size (number of references) can be set to any positive integer, keeping in mind the number of objects you cache and the number of available memory resources in your runtime environment. The default value is 1024.

The readOnly (read-only) property can be set to true or false. A read-only cache will return the same instance of the cache object to all callers. Therefore these objects cannot be modified. This provides a significant performance advantage. Read-write caches return a copy of the cached object (via serialization). This will be slower, but safe, so the default is false.

write at the end

1. Test code: cache

L2 cache

2. CacheInterface

public interface Cache {
    String getId();
    int getSize();
    void putObject(Object key, Object value);
    Object getObject(Object key);
    boolean hasKey(Object key);
    Object removeObject(Object key);
    void clear();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206105&siteId=291194637