mybaits二十三:二级缓存
二級緩存:(全局緩存),基于namespace級別的緩存,一個namespace對應(yīng)一個二級緩存
? 工作機制:?
? ? ? ? ? ? 1. 一個會話,查詢一條數(shù)據(jù),這個數(shù)據(jù)就會被放在當(dāng)前會話的一級緩存中.
? ? ? ? ? ? 2. 如果會話關(guān)閉,一級緩存中的數(shù)據(jù)會被保存到二級緩存中,新的會話查詢信息,就可以參照二級緩存的內(nèi)容
? ? ? ? ? ? 3. 不同的namespace,查出的數(shù)據(jù)放在自己對應(yīng)的緩存(map)中.
? ? ? ? ? ? mybatis查出的數(shù)據(jù)都會被默認(rèn)先放在一級緩存中,只有會話提交或關(guān)閉后,一級緩存中的數(shù)據(jù)才會轉(zhuǎn)移到二級緩存中。
? ?使用:
? ? ? 1. 開啟全局二級緩存配置 ?<setting name="cacheEnabled" value="true"/>
? ? ? 2. 在mapper.xml中配置使用二級緩存
<cache eviction="FIFO" flushInterval="60000" readOnly="false" size="1024" ></cache><!-- eviction:緩存的回收策略LRU-最近最少使用的, 移除最長時間不被使用的對象FIFO-先進先出, 按對象進入緩存的順序來移除它們SOFT-軟引用, 移除基于垃圾回收器轉(zhuǎn)態(tài)和軟引用規(guī)則的對象WEAK-弱引用, 更積極的移除基于垃圾收集器狀態(tài)和弱引用規(guī)則的對象默認(rèn)的是LRUflushInterval: 緩存刷新間隔緩存多長時間清空一次,默認(rèn)不清空, 設(shè)置的是一個毫秒值readOnly: 是否可讀true:只讀,mybatis認(rèn)為所有從緩存中獲取數(shù)據(jù)的操作都是只讀操作,不會修改數(shù)據(jù)mybatis為了加快獲取速度,直接就會將數(shù)據(jù)在緩存中的引用交給用戶,這樣不安全,但速度快false:非只讀,mybatis認(rèn)為獲取的數(shù)據(jù)可能會被修改mybatis會利用序列化和反序列化技術(shù)克隆一份新的數(shù)據(jù)給用戶, 這樣操作安全, 但是速度慢size:緩存存放多少元素type:指定自定義緩存的全類名自定義緩存需要實現(xiàn)Cache接口 -->? ? ? 3. POJO需要實現(xiàn)序列化接口? ? 二級緩存存放的內(nèi)容是數(shù)據(jù),而不是對象.所以 使用二級緩存的pojo需要實現(xiàn)序列化接口。
? ? ? ? ??public class Department implements Serializable{
? ? ? ? ? ? ?屬性?
? ? ? ? ? ?}
?
? ? 和緩存有關(guān)的設(shè)置/屬性
? ? ? ? ? ? 1). <setting name="cacheEnabled" value="false"/> ,false表示關(guān)閉緩存,但只關(guān)閉二級緩存,一級緩存依然可以使用
? ? ? ? ? ? 2). 每個select標(biāo)簽都有useCache="true",屬性, 如果改為false,表示不使用緩存(一級緩存依然使用,二級緩存不使用)
<select id="getEmpByDepnos" resultMap="defineEmp" useCache="true">select * from emptest a where empno = #{empno}</select>? ? ? ? ? ? ? ?3).每個增刪改標(biāo)簽的flushCache="true"
<insert id="addEmp" flushCache="true">insert into emptest(empno, ename, job, mgr,hiredate,sal) values( #{empno}, #{ename}, #{job}, #{mgr}, #{hiredate}, #{sal} )</insert>? ? ? ? ? ? ? ?增刪改執(zhí)行完成后,就會清除緩存. ? ?一旦執(zhí)行增刪改操作 ,如果flushCache="true",那么一級緩存就會清空,二級緩存也會被清空.
? ? ? ? ? ? ?4) 查詢標(biāo)簽也有?flushCache="false",默認(rèn)為false, 如果改為true, 那么每次查詢之前都會清空緩存,緩存就不會被使用。
? ? ? ? ? ? ?5).?SqlSession對象的clearCache()方法只是清楚當(dāng)前session的一級緩存. 不會清楚二級緩存.
? ?
測試:
@Testpublic void testSecondLevelCache() throws IOException, ParseException{String resource = "mybatis-config.xml";InputStream ins = Resources.getResourceAsStream(resource);SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);SqlSession openSession = sf.openSession();SqlSession openSession2 = sf.openSession();try{EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);Employee e1 = em.getEmpByDepnos(7369);// 關(guān)閉會話openSession.close(); // 第二次查詢是從二級緩存中拿到的數(shù)據(jù),并沒有發(fā)送新的sqlEmployeePlusMapper em2 = openSession2.getMapper(EmployeePlusMapper.class);Employee e2 = em2.getEmpByDepnos(7369);System.out.println(e1);System.out.println(e2);}finally{openSession.close();}}?
總結(jié)
以上是生活随笔為你收集整理的mybaits二十三:二级缓存的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jvm八:接口初始化规则
- 下一篇: mybaits二十四:缓存原理示意图