一、概述:
- 下载地址:https://github.com/mybatis/ehcache-cache
- 目录结构:
- lib文件夹中添加jar包:ehcache-core-2.6.8.jar mybatis-ehcache-1.0.3.jar slf4j-api-1.6.1.jar slf4j-simple-1.6.1.jar
- 全局配置文件mybatis-config.xml:开启缓存(开启方法同五、mybatis两级缓存中使用步骤中的配置文件);
- config源文件中添加ehcache.xml
- 对应的XXXMapper.xml中添加:
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
- 引用缓存:例如DepartmentMapper.xml 引用 EmployeeMapper.xml中的缓存:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.DepartmentMapper">
<!-- 引用缓存:namespace:指定和哪个名称空间下的缓存一样 -->
<cache-ref namespace="dao.EmployeeMapper" /> <select id="getDepartmentById"
resultType="introduction.Department">
SELECT * FROM TBL_DEPARTMENT WHERE ID= #{id}
</select>
</mapper>
二、ehcache.xml
1.ehcache.xml文件:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
4 <!-- 磁盘保存路径 -->
5 <diskStore path="log/ehcache" />
6
7 <defaultCache
8 maxElementsInMemory="1000"
9 maxElementsOnDisk="10000000"
10 eternal="false"
11 overflowToDisk="true"
12 timeToIdleSeconds="120"
13 timeToLiveSeconds="120"
14 diskExpiryThreadIntervalSeconds="120"
15 memoryStoreEvictionPolicy="LRU">
16 </defaultCache>
17 </ehcache>
18
View Code
2.ehcache.xm属性说明
- diskStore:指定数据在磁盘中的存储位置。
- defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
以下属性是必须的:
- maxElementsInMemory - 在内存中缓存的element的最大数目
- maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
- eterna- 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
- overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
以下属性是可选的:
- timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
- timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
- diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
- diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
- diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
- memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
三、实例验证:
1.一级缓存实例验证:
接口文件EmployeeMapper.java:
1 void addEmp(Employee employee);
2
3 Employee getEmpById(int
映射文件EmployeeMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="dao.EmployeeMapper">
6 <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> 7
8 <insert id="addEmp" parameterType="entity.Employee" useGeneratedKeys="true" keyProperty="id">
9 insert into tbl_employee(last_name,gender,email) values(
10 #{lastName},#{gender},#{email}
11 )
12 </insert>
13
14 <select id="getEmpById" parameterType="Integer" resultType="entity.Employee">
15 select LAST_NAME AS
16 lastName,gender as gender,email as email from
17 tbl_employee where id =#{asdsdfsdf}
18 </select>
19
20 </mapper>
junit测试类:
1 @Test
2 public void test02() {
3 String resource = "mybatis-config.xml";
4 SqlSession openSession = null;
5 SqlSession openSession2 = null;
6 try {
7 InputStream inputStream = Resources.getResourceAsStream(resource);
8 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
9 // 获取openSession 不会自动提交数据
10 openSession = sqlSessionFactory.openSession(true);
11 openSession2 = sqlSessionFactory.openSession(true);
12 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
13 Employee employee = mapper.getEmpByIdStepDis(1);
14 Employee employee1 = mapper.getEmpByIdStepDis(1);
15 System.out.println("测试一级缓存:" + employee);
16 System.out.println("测试一级缓存:" + employee1 + "," + (employee == employee1));
17
18 EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
19 Employee employee2 = mapper2.getEmpByIdStepDis(1);
20 System.out.println("sqlSession改变 一级缓存失效:" + employee2 + "," + (employee1 == employee2));
21 EmployeeMapper mapper23 = openSession2.getMapper(EmployeeMapper.class);
22 Employee employee23 = mapper23.getEmpByIdStepDis(2);
23 System.out.println("查询条件改变改变 一级缓存失效:" + employee23 + "," + (employee1 == employee23));
24
25 Employee emp = new Employee();
26 emp.setLastName("Tom");
27 emp.setGender("男");
28 emp.setEmail("678@qq.com");
29 mapper23.addEmp(emp);
30 Employee employee4 = mapper23.getEmpByIdStepDis(2);
31 System.out.println("查询条件相同+sqlSession相同 一级缓存失效:" + employee23 + "," + (employee4 == employee23));
32
33 Employee employee5 = mapper23.getEmpByIdStepDis(2);
34 openSession2.clearCache();
35 Employee employee6 = mapper23.getEmpByIdStepDis(2);
36 System.out.println("手动清楚缓存:" + (employee5 == employee6));
37 } catch (Exception e) {
38 // TODO: handle exception
39 } finally {
40 if (openSession != null) {
41 openSession.close();
42 }
43
44 }
45
View Code
运行结果:
测试一级缓存:Employee [id=1, lastName=joy33333, email=joy52112225@iclound.com, gender=女, dept=Department [id=1, departmentName=null]]
测试一级缓存:Employee [id=1, lastName=joy33333, email=joy52112225@iclound.com, gender=女, dept=Department [id=1, departmentName=null]],true
sqlSession改变 一级缓存失效:Employee [id=1, lastName=joy33333, email=joy52112225@iclound.com, gender=女, dept=Department [id=1, departmentName=null]],false
查询条件改变改变 一级缓存失效:Employee [id=2, lastName=joy2x22222, email=joy2x22222, gender=男, dept=null],false
查询条件相同+sqlSession相同 一级缓存失效:Employee [id=2, lastName=joy2x22222, email=joy2x22222, gender=男, dept=null],false
手动清楚缓存:false
2.二级缓存实例验证:
接口文件EmployeeMapper.java:同1级缓存实例验证
映射文件EmployeeMapper.xml:同1级缓存实例验证
junit测试类:
1 @Test
2 public void test08() {
3 String resource = "mybatis-config.xml";
4 SqlSession openSession = null;
5 SqlSession openSession2 = null;
6 try {
7 InputStream inputStream = Resources.getResourceAsStream(resource);
8 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
9 // 获取openSession 不会自动提交数据
10 openSession = sqlSessionFactory.openSession(true);
11 openSession2 = sqlSessionFactory.openSession(true);
12 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
13 EmployeeMapper mapper2 = openSession2.getMapper(EmployeeMapper.class);
14 Employee employee = mapper.getEmpById(1);
15
16 System.out.println("测试二级缓存:" + employee);
17 openSession.close();
18 Employee employee1 = mapper2.getEmpById(1);
19 System.out.println("测试二级缓存:" + employee1 + "," + (employee == employee1));
20 openSession2.close();
21 } catch (Exception e) {
22 // TODO: handle exception
23 } finally {
24 if (openSession != null) {
25 openSession.close();
26 openSession2.close();
27 }
28
29 }
30
View Code
运行结果:
测试二级缓存:Employee [id=null, lastName=joy33333, email=joy52112225@iclound.com, gender=女]
测试二级缓存:Employee [id=null, lastName=joy33333, email=joy52112225@iclound.com, gender=女],true
四、缓存文件查看:
我从来不相信什么懒洋洋的自由。我向往的自由是通过勤奋和努力实现的更广阔的人生。 我要做一个自由又自律的人,靠势必实现的决心认真地活着。