八 mybatis查询缓存(一级缓存,二级缓存)和ehcache整合

1       查询缓存

1.1     什么是查询缓存

mybatis提供查询缓存,用于减轻数据压力,提高数据库性能。

mybaits提供一级缓存,和二级缓存。

 

一级缓存是SqlSession级别的缓存。在操作数据库时需要构造 sqlSession对象,在对象中有一个数据结构(HashMap)用于存储缓存数据。不同的sqlSession之间的缓存数据区域(HashMap)是互相不影响的。

 

二级缓存是mapper级别的缓存,多个SqlSession去操作同一个Mapper的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。

 

为什么要用缓存?

如果缓存中有数据就不用从数据库中获取,大大提高系统性能。

 

1.2     一级缓存

1.2.1     一级缓存工作原理

 

第一次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,如果没有,从数据库查询用户信息。

得到用户信息,将用户信息存储到一级缓存中。

 

如果sqlSession去执行commit操作(执行插入、更新、删除),清空SqlSession中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。

 

第二次发起查询用户id为1的用户信息,先去找缓存中是否有id为1的用户信息,缓存中有,直接从缓存中获取用户信息,如果没有查询数据库。

 

1.2.2     一级缓存测试

mybatis默认支持一级缓存,不需要在配置文件去配置。

 

按照上边一级缓存原理步骤去测试。

 

 1  public void testCache1() throws Exception{
 2 
 3           SqlSession sqlSession = sqlSessionFactory.openSession();//创建代理对象
 4 
 5           UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
 6 
 7          
 8           //下边查询使用一个SqlSession
 9 
10           //第一次发起请求,查询id为1的用户
11 
12           User user1 = userMapper.findUserById(1);
13           System.out.println(user1);
14 
15          
16 
17 //        如果sqlSession去执行commit操作(执行插入、更新、删除),清空SqlSession中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。
18 
19 
20           //更新user1的信息
21 
22           user1.setUsername("测试用户22");
23           userMapper.updateUser(user1);
24 
25           //执行commit操作去清空缓存
26 
27           sqlSession.commit();
28 
29          
30 
31           //第二次发起请求,查询id为1的用户
32 
33           User user2 = userMapper.findUserById(1);
34           System.out.println(user2);
35 
36           sqlSession.close();
37 
38        }

 

1.2.3     一级缓存应用

 

正式开发,是将mybatis和spring进行整合开发,事务控制在service中。

一个service方法中包括 很多mapper方法调用。

 

service{

         //开始执行时,开启事务,创建SqlSession对象

         //第一次调用mapper的方法findUserById(1)

        

         //第二次调用mapper的方法findUserById(1),从一级缓存中取数据

         //方法结束,sqlSession关闭

}

 

如果是执行两次service调用查询相同 的用户信息,不走一级缓存,因为session方法结束,sqlSession就关闭,一级缓存就清空。

 

1.3     二级缓存

1.3.1     原理

 

首先开启mybatis的二级缓存。

 

sqlSession1去查询用户id为1的用户信息,查询到用户信息会将查询数据存储到二级缓存中。

 

如果SqlSession3去执行相同 mapper下sql,执行commit提交,清空该 mapper下的二级缓存区域的数据。

 

sqlSession2去查询用户id为1的用户信息,去缓存中找是否存在数据,如果存在直接从缓存中取出数据。

 

二级缓存与一级缓存区别,二级缓存的范围更大,多个sqlSession可以共享一个UserMapper的二级缓存区域。

UserMapper有一个二级缓存区域(按namespace分) ,其它mapper也有自己的二级缓存区域(按namespace分)。

每一个namespace的mapper都有一个二缓存区域,两个mapper的namespace如果相同,这两个mapper执行sql查询到数据将存在相同 的二级缓存区域中。

 

 

1.3.2     开启二级缓存

 

mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓存。

 

在核心配置文件SqlMapConfig.xml中加入

1 <setting name="cacheEnabled" value="true"/>

 

描述

允许值

默认值

cacheEnabled

对在此配置文件下的所有cache 进行全局性开/关设置。

true false

true

 

在UserMapper.xml中开启二缓存,UserMapper.xml下的sql执行完成会存储到它的缓存区域(HashMap)。

1 <!-- 开启本mapper的namespace下的二级缓存 -->
2     <cache/>

 

1.3.3     调用pojo类实现序列化接口

 1 public class User implements Serializable{
 2     private Integer id;
 3 
 4     private String username;
 5 
 6     private Date birthday;
 7 
 8     private String sex;
 9 
10     private String address;
11     
12     private List<Orders> ordersList;

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

 

1.3.4     测试方法

 1 // 二级缓存测试
 2     @org.junit.Test
 3        public void testCache2() throws Exception {
 4 
 5           SqlSession sqlSession1 = sqlSessionFactory.openSession();
 6           SqlSession sqlSession2 = sqlSessionFactory.openSession();
 7           SqlSession sqlSession3 = sqlSessionFactory.openSession();
 8 
 9           // 创建代理对象
10           UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
11 
12           // 第一次发起请求,查询id为1的用户
13           User user1 = userMapper1.findUserById(1);
14           System.out.println(user1);
15 
16 
17           //这里执行关闭操作,将sqlsession中的数据写到二级缓存区域
18           sqlSession1.close();
19          
20          
21 
22           //使用sqlSession3执行commit()操作
23           UserMapper userMapper3 = sqlSession3.getMapper(UserMapper.class);
24          
25           User user  = userMapper3.findUserById(1);
26           user.setUsername("张明明");
27 
28           userMapper3.updateUser(user);
29 
30           //执行提交,清空UserMapper下边的二级缓存
31 
32           sqlSession3.commit();
33           sqlSession3.close();
34 
35 
36           UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
37 
38           // 第二次发起请求,查询id为1的用户
39           User user2 = userMapper2.findUserById(1);
40           System.out.println(user2);
41 
42 
43           sqlSession2.close();
44        }

 

1.3.5     useCache配置

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

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

 

总结:针对每次查询都需要最新的数据sql,要设置成useCache=false,禁用二级缓存。

 

1.3.6     刷新缓存(就是清空缓存)

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

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

如下:

1 <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User" flushCache="true">

 

总结:一般下执行完commit操作都需要刷新缓存,flushCache=true表示刷新缓存,这样可以避免数据库脏读。

 

1.4     mybatis整合ehcache

 

ehcache是一个分布式缓存框架。

 

1.4.1     分布缓存

我们系统为了提高系统并发,性能、一般对系统进行分布式部署(集群部署方式)

 

不使用分布缓存,缓存的数据在各各服务单独存储,不方便系统 开发。所以要使用分布式缓存对缓存数据进行集中管理。

 

mybatis无法实现分布式缓存,需要和其它分布式缓存框架进行整合。

 

1.4.2     整合方法(掌握)

 

mybatis提供了一个cache接口,如果要实现自己的缓存逻辑,实现cache接口开发即可。

 

mybatis和ehcache整合,mybatis和ehcache整合包中提供了一个cache接口的实现类。

 1 public interface Cache {
 2 
 3   /**
 4    * @return The identifier of this cache
 5    */
 6   String getId();
 7 
 8   /**
 9    * @param key Can be any object but usually it is a {@link CacheKey}
10    * @param value The result of a select.
11    */
12   void putObject(Object key, Object value);
13 
14   /**
15    * @param key The key
16    * @return The object stored in the cache.
17    */
18   Object getObject(Object key);
19 
20   /**
21    * Optional. It is not called by the core.
22    * 
23    * @param key The key
24    * @return The object that was removed
25    */
26   Object removeObject(Object key);
27 
28   /**
29    * Clears this cache instance
30    */  
31   void clear();
32 
33   /**
34    * Optional. This method is not called by the core.
35    * 
36    * @return The number of elements stored in the cache (not its capacity).
37    */
38   int getSize();
39   
40   /** 
41    * Optional. As of 3.2.6 this method is no longer called by the core.
42    *  
43    * Any locking needed by the cache must be provided internally by the cache provider.
44    * 
45    * @return A ReadWriteLock 
46    */
47   ReadWriteLock getReadWriteLock();
48 
49 }

 

mybatis默认实现cache类是:PerpetualCache

 1 /**
 2  * @author Clinton Begin
 3  */
 4 public class PerpetualCache implements Cache {
 5 
 6   private String id;
 7 
 8   private Map<Object, Object> cache = new HashMap<Object, Object>();
 9 
10   public PerpetualCache(String id) {
11     this.id = id;
12   }
13 
14   public String getId() {
15     return id;
16   }
17 
18   public int getSize() {
19     return cache.size();
20   }
21 
22   public void putObject(Object key, Object value) {
23     cache.put(key, value);
24   }
25 
26   public Object getObject(Object key) {
27     return cache.get(key);
28   }

 

1.4.3     加入ehcache包

 

1.4.4     整合ehcache

配置mapper中cache中的type为ehcache对cache接口的实现类型。

 public final class org.mybatis.caches.ehcache.EhcacheCache implements org.apache.ibatis.cache.Cache {

1     <!-- 开启本mapper的namespace下的二缓存
2     type:指定cache接口的实现类的类型,mybatis默认使用PerpetualCache
3     要和ehcache整合,需要配置type为ehcache实现cache接口的类型
4      -->
5     <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

1.4.5     加入ehcache的配置文件

 

在classpath下配置ehcache.xml

 1 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2     xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 3     <diskStore path="F:\develop\ehcache" />
 4     <defaultCache 
 5         maxElementsInMemory="1000" 
 6         maxElementsOnDisk="10000000"
 7         eternal="false" 
 8         overflowToDisk="false" 
 9         timeToIdleSeconds="120"
10         timeToLiveSeconds="120" 
11         diskExpiryThreadIntervalSeconds="120"
12         memoryStoreEvictionPolicy="LRU">
13     </defaultCache>
14 </ehcache>

 

1.5     二级应用场景

对于访问多的查询请求且用户对查询结果实时性要求不高,此时可采用mybatis二级缓存技术降低数据库访问量,提高访问速度,业务场景比如:耗时较高的统计分析sql、电话账单查询sql等。

实现方法如下:通过设置刷新间隔时间,由mybatis每隔一段时间自动清空缓存,根据数据变化频率设置缓存刷新间隔flushInterval,比如设置为30分钟、60分钟、24小时等,根据需求而定

 

1.6     二级缓存局限性

         mybatis二级缓存对细粒度的数据级别的缓存实现不好,比如如下需求:对商品信息进行缓存,由于商品信息查询访问量大,但是要求用户每次都能查询最新的商品信息,此时如果使用mybatis的二级缓存就无法实现当一个商品变化时只刷新该商品的缓存信息而不刷新其它商品的信息,因为mybaits的二级缓存区域以mapper为单位划分,当一个商品信息变化会将所有商品信息的缓存数据全部清空。解决此类问题需要在业务层根据需求对数据有针对性缓存。

 

项目源码:

链接:http://pan.baidu.com/s/1bpmSbON 密码:sf3x

posted @ 2016-11-05 20:24  海天依色  阅读(390)  评论(0编辑  收藏  举报