cool hit counter MyBatis Level 2 Cache Principle Explained_Intefrankly

MyBatis Level 2 Cache Principle Explained


myBatis ofLevel 2 buffer memory beApplication grade of buffer memory, It can improve access to database queries of efficiency, to improve the application of performance。 This article will provide a comprehensive analysis ofMyBatis ofLevel 2 buffer memory of Design Principles。

1.myBatis of buffer memory Overall design of the mechanism and secondary buffer memory of working mode

As shown in the picture above, When opening a session, anSqlSession object will use aExecutor object to complete session operations,MyBatis ofLevel 2 buffer memory machine processed of The point is. be For thisExecutor make a fuss over a target。 If the user has configured the"cacheEnabled=true", or soMyBatis in providingSqlSession Object creationExecutor object, would be interested inExecutor object plus a decorator:CachingExecutor, at this timeSqlSession useCachingExecutor object to complete the operation request。CachingExecutor For query requests, will first determine that the query request is in theApplication grade ofLevel 2 buffer memory in be not have buffer memory result, If there are search results, then return directly to buffer memory result; in case buffer memory There's nothing in it., And then to the real ofExecutor object to complete the query operation, laterCachingExecutor will bring the realExecutor return to of The query results are placed in the buffer memory in, Then after returning to the user。

CachingExecutor beExecutor of decorators to enhance theExecutor to make it function as a cached query, here the decorator pattern of the design pattern is used, the

CachingExecutor harmonyExecutor The relationship between the interfaces of the following classes is shown in the following diagram.

2 . mybatisLevel 2 buffer memory of divide

MyBatis not at all be Simply for the entireApplication There's only one.cache buffer memory targets, It will buffer memory divide of finer, i.e. beMapper grade of, That is, each of theMapper Both can have aCache The objects are specified as follows:

b. severalMapper Share aCache buffer memory targets( Using the Node Configuration)

If you want to make multipleMapper One for public useCache words, you can use nodes to specify your thisMapper Which one was used toMapper ofCache buffer memory

3.Using L2 cache, must-have conditions

MyBatis secondary buffer memory of Very fine granularity of support, It will specify a certain query statement be No use of secondary buffer memory。

Although theMapper configured in, and for that reasonMapper allocatedCache targets, This does not mean that we useMapper defined in of The query statement looks up of The results are placed in theCache partner, We must specifyMapper in of A certain selection statement be not supported buffer memory, That is, as follows, (located) at Configuration in the nodeuseCache="true",Mapper That's what this is all about.Select of Enquiry Support buffer memory characteristics, if not, There will be no such thing.Select inquiry, It won't go throughCache buffer memory。 as shown below,Select statement is configured with theuseCache="true", then this indicates that thisSelect statement of The query will use the secondary buffer memory。

in conclusion, To make a certain articleSelect Query Support Level 2 buffer memory, You need to make sure:

4. first class buffer memory harmonyLevel 2 buffer memory of Order of use

Please note, If you ofMyBatis Secondary used buffer memory, And you. ofMapper harmonyselect statement is also configured to use the secondary buffer memory, Then in the execution ofselect inquiry of length of time,MyBatis It will start with the secondary buffer memory take the input from, only secondly be first class buffer memory, i.e.MyBatis Query Data of sequential be:

5.Level 2 buffer memory realize of option

1.MyBatis Self-provided ofLevel 2 buffer memory of realize

MyBatis Itself offers a wealth of of, And powerful ofLevel 2 buffer memory of realize, It has a range of ofCache Interface Decorator, A wide range of applications can be accommodated for buffer memory operations harmony update of strategy。

MyBatis Defines a large number of ofCache of Decorators to enhance theCache buffer memory of functionalities, The following class diagram shows。

For eachCache with regard (preceding phrase), All have a capacity limit,MyBatis Each offers a variety of strategies to combatCache buffer memory of Capacity is controlled, as well as toCache in of Data is refreshed harmony permutation (math.)。 Here's a look at the different replacement strategy implementation classes of source code (computing):

MyBatis source code analysis - Cache interface and implementation of the Cache interface

MyBatis in ofCache withSPI realize, For those who need to integrate otherCache Or customizeCache Provides an interface。

img

Cache Implementation

Cache implementation class, Cache has different functions, each function independent, do not affect each other, then for different Cache function, here using the decorator pattern implementation.

PerpetualCache

as the foundation of buffer memory kind, The underlying implementation is simple, Directly usedHashMap。

FifoCache

FIFO recycling strategy, decorated class, maintains an internal queue to guarantee FIFO, and once the specified size is exceeded, fetches the Key from the queue and removes the key-value pair from the wrapped Cache.

LoggingCache

Logging function, decorated class for logging cache hits and outputting a hit log if DEBUG mode is enabled.

LruCache

LRU recycling strategy, decorated class that holds a LinkedHashMap internally to implement LRU.

ScheduledCache

Empty regularlyCache, but be Did not start a scheduled task, whereas be In useCache of length of time, to check the time be No, I'm here。

SynchronizedCache

Synchronized Cache, which is relatively simple to implement, directly uses the synchronized modifier method.

SoftCache

Soft reference recycling policy, Soft references are collected by the garbage collector only when there is not enough memory。 Over here of implementation mechanism, A linked table is used to guarantee a certain number of of Value will not be reclaimed even if memory is low, but be Not kept in that chain table of value is likely to be recalled。

(located) atWeakHashMap in, As you can see be Apply the reference toKey of, whileKey After being recycled, the correlation is removed ofValue。 but be Over here be Apply it toValue in, BecauseKey Cannot be recycled, If removed of speech, will affect the whole system, At the bottom of Implement the useHashMap realize of, NoKey, There is no way to remove the correlation of value。 Turn, The value is recycled, Put the soft reference object in the queue, Can be based onKey invokeremoveObject Remove the association of key harmony Soft reference object。

WeakCache

Weak reference recycling policy, Weak reference of Once an object is discovered by a garbage collector, will be recycled, Whether memory be not sufficient。 Over here of realize harmony on top of of Soft references are similar, In addition to usingWeakReference swap outSoftReference, The others are basically the same。 There's one more thing I can't figure out of only be, WhySoftCache It's locked, And there's no lock here。

TransactionalCache

affairs buffer memory, In the commit of length of time, It's true of Put it inCache in, Or roll back of time to clear it off, RightCache No impact。

SerializedCache

Serialization, Serialize the value and save it buffer memory in。 This feature is used buffer memory Return an instance ofCopy, Used to save thread safety。

2. User-defined Cache interface implementation

(located) atMapper The customization is used in the configuration of the file of buffer memory targets, as:

The tests were as follows.

The log output is as follows.

you can see it, Before each query to the database,MyBatis will be there first buffer memory Look for it in be No, there is no such thing buffer memory targets。 Only if the call tocommit() approach,MyBatis only then will buffer memory Write data in, Data logging of keyed to format, The value is the return of the of The value of the object。

3. with third-party memory buffer memory storehouse of integration(Ehcache)

Tools needed for MyBatis integration with Ehcache: https://gitee.com/sixiaojie/codes/hgumrf4k8ew2v1cjyqn7o57

1.Adding the ehcache package

ehcache-core-2.6.5.jar harmonymybatis-ehcache-1.0.2.jar

an beehcache Myself of, an be harmonymybatis of Consolidate packages

2.Integrating ehcache

Configure the type in cache in mapper to be the type of ehcache's implementation of the cache interface.

We're heremybatis-ehcache-1.0.2.jar find it beloworg.mybatis.caches.ehcache There's one under the bagEhcacheCache.class kind, That's it beehcache conformitymybatis ofCache interface of realize

UserMapper.xml:

3.Add the ehcache configuration file

Configure ehcache.xml under the classpath

The code is as follows.

4.ehcache.xml property configuration details

1. diskStore : Specify the location of the data (.data and .index) storage, you can specify the location of the folder on the disk

2、defaultCache : Default management policy

One、 The following properties be Have to of:

1. name: The name of the Cache, must be unique (ehcache will put this cache into a HashMap).

2、maxElementsInMemory: In memory buffer memory ofelement of The maximum number。

3、maxElementsOnDisk: On disk buffer memory ofelement of The maximum number, The default is0, Indicates no restrictions。

4、eternal: Set buffer memory ofelements be No, it's never going to expire。 If it istrue, follow buffer memory of Data always valid, If it isfalse Then also according totimeToIdleSeconds,timeToLiveSeconds judgements。

5. overflowToDisk: if the data in memory exceeds the memory limit, whether to cache it to disk.

2、 The following properties be selectable of:

1, timeToIdleSeconds: object idle time, the object will expire after how long it has not been accessed. Only valid for eternal to false. The default value of 0 indicates that access is always available.

2, timeToLiveSeconds: object survival time, the object from the creation to the time required to expire. Only valid for eternal to false. The default value of 0 indicates that access is always available.

3、diskPersistent: be No persists on disk。 Refers to the restartjvm after, data be No valid。 The default isfalse。

4. diskExpiryThreadIntervalSeconds: The object detects the thread runtime interval. How often the thread that identifies the state of the object runs.

5. diskSpoolBufferSizeMB: The size of the disk used by DiskStore, default value 30MB. Each cache uses its own DiskStore.

6、memoryStoreEvictionPolicy: If the data in memory exceeds the memory limit, to disk buffer memory time of strategy。 The defaultLRU, selectableFIFO、LFU。

Three、 buffer memory of3 kind of emptying policy :

1, FIFO , first in first out (first in first out).

2、LFU , Less Frequently Used ( Use at least). meaning be has been used at least of。 buffer memory of There is one elementhit attribute,hit The value is minimal of will be cleared out buffer memory。

3、LRU ,Least Recently Used( Least recently used, That is, it has not been used for the longest time). (ehcache The default). buffer memory of The element has a timestamp, while buffer memory The capacity is full, and need to make room buffer memory new of element of length of time, Then the existing buffer memory The element with the timestamp furthest from the current time of Elements will be cleared out buffer memory。

Think this article is good, Give me a compliment.~~ you of encourage, be I continue to share knowledge of Powerful power!

If you think something is wrong or incorrect, please do not hesitate to ask!


Recommended>>
1、Doityourself Shell multiprocess nesting
2、Another black technology has come out of nowhere and mobile phones may be replaced
3、DS7400 Mainframe General Programming
4、Its only a matter of time before robots have consciousness or destroy humanity
5、The Next Generation Finance Cloud Accounting for No One Finance for Everyone

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号