Mybatis study concluded (nine) - the query cache

First, what is the query cache

mybatis provide query cache, the data used to reduce stress and improve database performance. mybaits provide a cache and secondary cache.

1, a cache is sqlSession level cache. In operation configuration database requires sqlSession object has a data structure (the HashMap) in a subject, for storing cached data. Cache area (the HashMap) between different sqlSession is noninteracting.

2, a secondary cache mapper level cache, a plurality of the same to operate sqlSession Mapper sql statement, a plurality of common secondary cache can SqlSession, sqlSession across the secondary cache.

3. Why use a cache?
If there is data in the cache would not get from the database, reducing the number of interactions between the data and greatly improve system performance.

Second, the cache

1, a cache works

(1) The first time a user initiates a query for a user id information 1, the first to find the cache if there is information for the user id 1, if not, the query user information from the database. To give the user information, the user information stored in the cache.

(2) If sqlSession to perform commit operations (insert, update, delete), empty the cache SqlSession the purpose of doing so in order to allow stored in the cache is the latest information, avoid dirty reads.

(3). The second inquiry initiated by the user information for the user id 1, first to find the cache if there is information for the user id 1, the cache there, users get information directly from the cache. mybatis support a default cache. Testing is simple, there is not posted code.

2, a cache of applications

Formal development, if the project is to integrate the development mybatis and spring ...., transaction control in service in. A service approach includes many mapper method call.

Copy the code
service { 

 // When started, open a transaction, create SqlSession objects 

 // first call mapper method findUserById (1) 

 // second call mapper method findUserById (1), taking data from a cache 

 // the method ends, sqlSession Close 

}
Copy the code

If the user is performing the same information twice service inquiry calls, do not go cache, since the end of the session method, sqlSession closed, empty the cache on.

Third, the secondary cache

1, the secondary cache works

(1) First open the second-level cache mybatis.

(2). SqlSession1 to query a user id information for the user, query the user information query data will be stored in the secondary cache.

(3) If the mapper SqlSession3 to perform the same sql, commit the execution, clearing the data in the secondary cache area of ​​the mapper.

(4). SqlSession2 to query the user id information for the user 1, to find whether there is data to the cache, if there is data taken directly from the cache.

A secondary cache and cache difference, the greater the range of the secondary cache, the plurality of level two cache may be shared sqlSession UserMapper of a region.

UserMapper a secondary cache area (divided by namespace), the other two have their own mapper cache area (divided by namespace). Each namespace in a mapper has two cache area, the mapper namespace if two identical, these two perform sql mapper queries to the same data will be in the secondary cache area.

2, open secondary cache

Secondary cache is mybaits mapper level range, in addition to the main switch disposed in the SqlMapConfig.xml secondary cache, but also to open the second-level cache mapper.xml in particular. Adding core profile in SqlMapConfig.xml

<setting name="cacheEnabled" value="true"/>
  描述 允许值 默认值
cacheEnabled 对在此配置文件下的所有cache 进行全局性开/关设置。 true | false true

 

 

 

 

a.在mybatis的核心配置文件sqlMapConfig.xml中开启二级缓存,其实默认值就为true,写上方便代码维护。

<!-- 全局参数的配置 -->
<settings>
    <!-- 开启二级缓存 -->
    <setting name="cacheEnabled" value="true"/>
</settings> 

b.实体类User实现序列化接口

public class User implements Serializable{
  //属性......
  //getter and setter......  
}

为了将缓存数据取出执行反序列化操作,因为二级缓存数据存储介质多种多样,不一定在内存。

c.Junit测试:

Copy the code
/**
 * 二级缓存测试
 * @throws Exception
 */
@Test
public void testCache() throws Exception{
    SqlSession sqlSession1 = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    SqlSession sqlSession3 = sqlSessionFactory.openSession();
    // 创建代理对象
    UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
    // 第一次发起请求,查询id为1的用户
    User user1 = userMapper1.findUserById(1);
    System.out.println(user1);

    //这里执行关闭操作,将sqlsession中的数据写到二级缓存区域
    sqlSession1.close();
    
    //使用sqlSession3执行commit()操作
    UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
    User user  = userMapper3.findUserById(1);
    user.setUsername("张明明");        
    userMapper3.updateUser(user);
    //执行提交,清空UserMapper下边的二级缓存
    sqlSession3.commit();
    sqlSession3.close();

    UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
    // 第二次发起请求,查询id为1的用户
    User user2 = userMapper2.findUserById(1);
    System.out.println(user2);

    sqlSession2.close();
}
Copy the code

3、禁用二级缓存

在statement中设置useCache=false可以禁用当前select语句的二级缓存,即每次查询都会发出sql去查询,默认情况是true,即该sql使用二级缓存。

<select id="findOrderListResultMap" resultMap="ordersUserMap" useCache="false">

4、刷新缓存

在mapper的同一个namespace中,如果有其它insert、update、delete操作,操作数据完成后需要刷新缓存,如果不执行刷新缓存会出现脏读。

设置statement配置中的flushCache="true" 属性,默认情况下为true即刷新缓存,如果改成false则不会刷新。使用缓存时如果手动修改数据库表中的查询数据会出现脏读。

如下:

<insert id="insertUser" parameterType="com.mybaits.entity.User" flushCache="true">

5、Mybatis Cache参数

flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。

size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的可用内存资源数目。默认值是1024。

readOnly(只读)属性可以被设置为true或false。只读的缓存会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false。

如下例子:

<cache  eviction="FIFO"  flushInterval="60000"  size="512"  readOnly="true"/>

这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会导致冲突。可用的收回策略有, 默认的是 LRU:

(1) .LRU - Least Recently Used: Removes objects longest time without being used.
(2) .FIFO - FIFO: an object into the cache in order to remove them.
(3) .SOFT - Soft Reference: Removes objects based on the garbage collector state and rules of soft references.
(4) .WEAK - Weak Reference: More aggressively removes objects referenced rule-based garbage collector state and weak. 

6, the secondary cache scenarios

     For access to more user queries and less demanding real-time query results, this time can be mybatis secondary cache technology to reduce database traffic and improve access speed, business scenarios such as: time-consuming higher statistical analysis sql, phone bills sql queries and so on.

    Method is as follows: by setting the refresh interval, the cache mybatis automatically emptied at regular intervals, the frequency setting according to the data cache refresh interval flushInterval changes, such as to 30 minutes, 60 minutes, 24 hours, etc., according to demand.

7, the secondary cache limitations

     mybatis secondary cache data cache for fine-grained level of implementation is not good, such as the following requirements: information on the goods cache, since the goods large query access information, but requires the user to query every time the latest product information at this time if use mybatis secondary cache can not be achieved only flushes the cache information of the merchandise when a product changes without refreshing the information of other commodities, because the secondary cache area mybaits to mapper units of division, when a commodity information will change all all product information data cache emptied. The need to solve such problems in the business layer according to the needs of targeted cache data.

 

Guess you like

Origin www.cnblogs.com/cdchencw/p/12303546.html