Spring+springmvc+mybatis Deep learning and building (eight)--mybatis query cache

Source: Internet
Author: User
Tags serialization

1. What is a query cache

MyBatis provides query caching to mitigate database stress and improve database performance.

MyBatis provides a first-level cache and a level two cache.

The first-level cache is a cache at the sqlsession level. The Sqlsession object needs to be constructed when manipulating the database, and there is a data structure (HASHMAP) in the object that stores the cached data. The cache data regions (HASHMAP) between different sqlsession are not affected by each other.

The second level cache is mapper level cache, multiple sqlsession to operate the same mapper SQL statement, multiple sqlsession can share a level two cache, level two cache is across sqlsession.

Why use caching?

If there is data in the cache, it is not taken from the database, which greatly improves the system performance.

2. First-level cache 2.1-tier caching how it works

For the first time, the user ID 1 is queried to find out if there is an ID of 1 user information in the cache, and if not, the user information is queried from the database.

Get the user information and store the user information in the first level cache.

If sqlsession goes to commit (INSERT, UPDATE, delete), empties the first-level cache in the sqlsession so that the cache is stored with the most up-to-date information and avoids dirty reads.

The second time to query user ID 1 user information, first to find out if the cache has ID 1 user information, the cache has, directly from the cache to obtain user information.

2.2 Level Cache Testing

MyBatis supports first-level caching by default and does not need to be configured in configuration files.

Follow the top-level caching principle step to test.

@Test Public voidTestCache1 ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); Usermapper Usermapper=sqlsession.getmapper (Usermapper.class); //The bottom query uses a sqlsession//the first time the request is initiated, the user with the ID 1 is queriedUser User1=usermapper.finduserbyid (1);                System.out.println (user1); //if sqlsession goes to commit (performs INSERT, UPDATE, delete), empties the first level cache in Sqlsession,//The purpose of this is to allow the cache to store the most up-to-date information and avoid dirty reads. //Update user1 informationUser1.setusername ("Test user 22");        Usermapper.updateuser (user1); //perform a commit operation to empty the cacheSqlsession.commit (); //second launch request, query for user with ID 1User User2=usermapper.finduserbyid (1);        System.out.println (User2);    Sqlsession.close (); }
2.3 Level Cache Application

Formal development is the integration of MyBatis and spring, and transaction control in the service.

A service method includes many Mapper method calls.

service{

Start execution, open transaction, create Sqlsession object

Method of calling Mapper for the first time Finduserbyid (1)

Second call to Mapper method Finduserbyid (1), fetching data from the first-level cache

Method End, Sqlsession close

}

If you are executing two service calls to query the same user information, do not go to the first level cache, because the session method ends, Sqlsession is closed, first-level cache is emptied.

3. Level Two cache 3.1 two cache principle

First, turn on the MyBatis level two cache.

SqlSession1 to query User ID 1 user information, query to user information regret to tell the query data stored in the level two cache.

If SqlSession3 executes SQL under the same mapper and commits a commit, the data for the level two cache area under that mapper is emptied.

SqlSession2 to query the user ID 1 user information, go to the cache to find out if there is data, if there is directly from the cache to remove data.

The second-level cache differs from the first-level cache: The two-level cache is larger in scope, and multiple sqlsession can share a usermapper two-level cache area. Usermapper has a level two cache area (by namespace), and the other mapper have their own level two cache area (by namespace).

Each namespace mapper has a level two cache area, two mapper namespace if the same, these two mapper execute SQL query to the data will exist in the same two-level cache area.

3.2 Turn on level two cache

MyBatis Level Two cache is the Mapper range level, in addition to the Sqlmapconfig.xml set level two cache of the total switch, but also in the specific mapper.xml to turn on the level two cache.

In the core configuration file Sqlmapconfig.xml, add:

<name= "cacheenabled"  value= "true"/>
Describe Allowed values Default value
Cacheenabled Global on/Off settings for all caches under this profile. True False False

A level two cache is turned on in Usermapper.xml, and the SQL execution under Usermapper.xml is stored in its cache area (HASHMAP) after completion.

3.3 Calling the Pojo class to implement the serialization interface

In order to take the cached data out to perform the deserialization operation, because the level two cache data storage medium is varied, not necessarily in memory. May be on hard disk, remote, etc.

3.4 Test methods
@Test Public voidTestCache2 ()throwsexception{sqlsession SqlSession1=sqlsessionfactory.opensession (); Sqlsession SqlSession2=sqlsessionfactory.opensession (); Sqlsession SqlSession3=sqlsessionfactory.opensession (); Usermapper UserMapper1=sqlsession1.getmapper (Usermapper.class); Usermapper UserMapper2=sqlsession2.getmapper (Usermapper.class); Usermapper UserMapper3=sqlsession3.getmapper (Usermapper.class); //the first time the request is initiated, the user with the ID 1 is queriedUser User1=usermapper1.finduserbyid (1);        System.out.println (user1); //The shutdown is performed here, and the data in Sqlsession is written to the level two cache areaSqlsession1.close (); //perform a commit () operation using SqlSession3User User=usermapper3.finduserbyid (1); User1.setusername ("Joanna");        Usermapper3.updateuser (user); //execute commit, empty the level two cache below UsermapperSqlsession3.commit ();                Sqlsession3.close (); //second launch request, query for user with ID 1User User2=usermapper2.finduserbyid (1);        System.out.println (User2);    Sqlsession2.close (); }
3.5 Disabling Level Two caching

Setting Usecache=false in statement disables the level two cache for the current SELECT statement, that is, each query emits SQL, which by default is true, that is, the SQL uses a level two cache.

<select id= "Findorderlistresultmap" resultmap= "Ordersusermap" usecache= "false" >

3.6 Refreshing the cache (that is, emptying the cache)

In the same namespace of mapper, if you have additional insert, UPDATE, delete operation data, you need to flush the cache, and dirty reads will occur if you do not perform a flush cache.

Setting the Flushcache= "true" property in the statement configuration, which is true by default, refreshes the cache and does not refresh if it is changed to false. When you use caching, dirty reads occur if you manually modify the query data in a database table.

<insert id= "Insertuser" parametertype= "Cn.itcast.mybatis.po.User" flushcache= "true" >

Summary: In general, the execution of the commit operation needs to flush the cache, flushcache=true means refreshing the cache, which avoids the database dirty read.

3.7 Mybatis Cache parameter

The Flushinterval (refresh interval) can be set to any positive integer, and they represent a reasonable millisecond in the form of a time end. The default is not set, and the situation does not have a flush interval, and the cache simply refreshes when the statement is invoked.

The 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 for the environment you are running. The default value is 1024.

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

Here's an example:

<cache eviction= "FIFO" flushinterval= "60000" size= "Up" readonly= "true"/>

This more advanced configuration creates a FIFO cache, refreshes every 60 seconds, saves 512 references to the resulting object or list, and the returned objects are considered read-only, so modifying them between callers in different threads can cause conflicts. The available retract policies are, by default, LRU:

    1. lru– Least Recently used: Removes objects that are not used for the longest time.
    2. fifo– FIFO: Removes them by the order in which they are entered in the cache.
    3. soft– Soft Reference: Removes objects based on the garbage collector state and soft reference rules.
    4. weak– Weak references: More aggressively remove objects based on the garbage collector state and weak reference rules.
4.mybatis Integrated Ehcache

Ehcache is a pure Java in-process cache framework, is a widely used open source Java distributed cache, with fast, capable and so on, is the default Cacheprovider hibernate.

4.1 Distributed Cache

In order to improve the system concurrency, performance, generally distributed deployment System (cluster deployment mode)

Without the use of distributed caching, cached data is stored separately in individual services and is inconvenient for system development. Therefore, the cached data is centrally managed using distributed caching.

MyBatis's specialty is the SQL operation, the management of the cached data is not MyBatis's specialty. MyBatis cannot implement distributed caching and needs to be integrated with other distributed cache frameworks, such as Redis, memcached, Ehcache, etc.

4.2 Integration Method (Master)

MyBatis provides a cache interface, and if you want to implement your own cache logic, implement the cache interface development.

MyBatis and Ehcache integration, the MyBatis and Ehcache integration packages provide an implementation class for the cache interface.

MyBatis the default cache implementation class is:

4.3 Add ehcache Pack

4.4 Integrated Ehcache

Configure the type of the cache in the mapper to be the implementation of the Ehcache to the cache interface.

4.5 Adding a Ehcache configuration file

Configure the Ehcache.xml under Classpath

<EhcacheXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:nonamespaceschemalocation=".. /config/ehcache.xsd ">    <DiskstorePath= "F:\develop\ehcache" />    <Defaultcachemaxelementsinmemory= "+"Maxelementsondisk= "10000000"Eternal= "false"Overflowtodisk= "false"Timetoidleseconds= "+"Timetoliveseconds= "+"Diskexpirythreadintervalseconds= "+"Memorystoreevictionpolicy= "LRU">    </Defaultcache></Ehcache>

Property Description:

Diskstore: Specifies where the data is stored on disk.

Defaultcache: When you create a cache with Cachemanager.add ("Democache"), Ehcache uses the management policy specified by <defaultCache/>.

The following properties are required:

Maxelementsinmemory: The maximum number of element that is cached in memory.

Maxelementsondisk: The maximum number of element that is cached on disk, or 0 for infinity.

Eternal: Sets whether the cached elements will never expire. If true, the cached data is always valid, and if False, you also have to interpret it according to Timetoidleseconds,timetoliveseconds.

Overflowtodisk: Sets whether the expired element is cached on disk when the memory cache overflows.

The following properties are optional:

Timetoidleseconds: When the data cached in the Ehcache is two times longer than the Timetoidleseconds property value, the data is deleted, and the default value is 0, which means that the idle time is infinitely large.

Timetoliveseconds: The valid lifetime of the cached element is 0 by default, which means that element has an infinite time to live.

DISKSPOOLBUFFERSIZEMB: This parameter sets the buffer size of the Diskstore (disk cache). The default is 30MB, and each cache should have its own buffer.

Diskpersistent: If the data in the disk save Ehcache is enabled when the VM restarts, the default is False.

Diskexpirythreadintervalseconds-Disk cache cleanup thread run interval, default is 120 seconds. Each 120s, the corresponding thread will perform a cleanup of the data in Ehcache.

Memorystoreevictionpolicy-When the memory cache is maximized and a new element is added, the policy of element in the cache is removed . The default is LRU (least recently used), with the optional LFU (least commonly used) and FIFO (first in, out).

4.6 Test Procedure

Same 3.4

4.7 Level Two cache scenario

Access to many query requests and users of the query results real-time requirements are not high, at this time can be used MyBatis two cache technology to reduce database access, improve access speed, business scenarios such as: time-consuming statistical analysis of SQL, telephone Bill query SQL.

The implementation is as follows: By setting the refresh interval, the cache is automatically emptied by mybatis at intervals, and the cache refresh interval is set according to the data change frequency flushinterval, for example, set to 30 minutes, 60 minutes, 24 hours, etc., depending on the needs.

4.8 Level Two cache limitations

MyBatis level Two cache for fine-grained data-level cache implementation is not good, such as the following requirements: The product information cache, because the product information query access is large, but require users every time can query the latest product information, At this point, if you use MyBatis's level two cache, you cannot realize that when a commodity changes, only the cache information of the product is refreshed and the information of other goods is not refreshed, because MyBatis's level two cache area is divided by mapper, and when an item information changes, the cached data of all commodity information is emptied. Solving such problems requires the re-business layer to target the data in a targeted cache based on demand.

Spring+springmvc+mybatis Deep learning and building (eight)--mybatis query cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.