020.Mybatis的二级缓存---(1)
1.Mybatis的二级缓存
2.怎样开启Mybatis的二级缓存
3.怎样开启Mybatis的二级缓存
3.1 在MybatisTest.java中测试一级缓存
/** * 测试一级缓存 * @throws Exception */ @Test public void testLv1Cache() throws Exception { SqlSession session = null; try{ session = MyBatisUtils.openSession(); Goods goods = session.selectOne("goods.selectById" , 1603); Goods goods1 = session.selectOne("goods.selectById" , 1603); System.out.println(goods.hashCode() + ":" + goods1.hashCode()); }catch (Exception e){ throw e; }finally { MyBatisUtils.closeSession(session); } try{ session = MyBatisUtils.openSession(); Goods goods = session.selectOne("goods.selectById" , 1603); session.commit();//commit提交时对该namespace缓存强制清空 Goods goods1 = session.selectOne("goods.selectById" , 1603); System.out.println(goods.hashCode() + ":" + goods1.hashCode()); }catch (Exception e){ throw e; }finally { MyBatisUtils.closeSession(session); } }
3.2 goods.xml中
<!--开启了二级缓存 eviction是缓存的清除策略,当缓存对象数量达到上限后,自动触发对应算法对缓存对象清除 1.LRU – 最近最久未使用:移除最长时间不被使用的对象。 O1 O2 O3 O4 .. O512 14 99 83 1 893 2.FIFO – 先进先出:按对象进入缓存的顺序来移除它们。 3.SOFT – 软引用:移除基于垃圾收集器状态和软引用规则的对象。 4.WEAK – 弱引用:更积极的移除基于垃圾收集器状态和弱引用规则的对象。 --> <cache eviction="LRU" flushInterval="600000" size="512" readOnly="true"/>
3.3 MybatisTest.java中测试二级缓存
/** * 测试二级缓存 * @throws Exception */ @Test public void testLv2Cache() throws Exception { SqlSession session = null; try{ session = MyBatisUtils.openSession(); Goods goods = session.selectOne("goods.selectById" , 1603); System.out.println(goods.hashCode()); }catch (Exception e){ throw e; }finally { MyBatisUtils.closeSession(session); } try{ session = MyBatisUtils.openSession(); Goods goods = session.selectOne("goods.selectById" , 1603); System.out.println(goods.hashCode()); }catch (Exception e){ throw e; }finally { MyBatisUtils.closeSession(session); } }