1、一級緩存
MyBatis 默認開啟了一級緩存,一級緩存是在SqlSession 層面進行緩存的。即,同一個SqlSession ,多次調用同一個Mapper和同一個方法的同一個參數,只會進行一次數據庫查詢,然后把數據緩存到緩沖中,以后直接先從緩存中取出數據,不會直接去查數據庫。
但是不同的SqlSession對象,因為不用的SqlSession都是相互隔離的,所以相同的Mapper、參數和方法,他還是會再次發送到SQL到數據庫去執行,返回結果。
2、二級緩存
為了克服這個問題,需要開啟二級緩存,是的緩存zaiSqlSessionFactory層面給各個SqlSession 對象共享。默認二級緩存是不開啟的,需要手動進行配置。
<cache/>
如果這樣配置的話,很多其他的配置就會被默認進行,如:
- 映射文件所有的select 語句會被緩存
- 映射文件的所有的insert、update和delete語句會刷新緩存
- 緩存會使用默認的Least Recently Used(LRU,最近最少使用原則)的算法來回收緩存空間
- 根據時間表,比如No Flush Interval,(CNFI,沒有刷新間隔),緩存不會以任何時間順序來刷新
- 緩存會存儲列表集合或對象(無論查詢方法返回什么)的1024個引用
- 緩存會被視為是read/write(可讀/可寫)的緩存,意味着對象檢索不是共享的,而且可以很安全的被調用者修改,不干擾其他調用者或縣城所作的潛在修改
可以在開啟二級緩存時候,手動配置一些屬性
<cache eviction="LRU" flushInterval="100000" size="1024" readOnly="true"/>
各個屬性意義如下:
- eviction:緩存回收策略
- LRU:最少使用原則,移除最長時間不使用的對象
- FIFO:先進先出原則,按照對象進入緩存順序進行回收
- SOFT:軟引用,移除基於垃圾回收器狀態和軟引用規則的對象
- WEAK:弱引用,更積極的移除移除基於垃圾回收器狀態和弱引用規則的對象 - flushInterval:刷新時間間隔,單位為毫秒,這里配置的100毫秒。如果不配置,那么只有在進行數據庫修改操作才會被動刷新緩存區
- size:引用額數目,代表緩存最多可以存儲的對象個數
- readOnly:是否只讀,如果為true,則所有相同的sql語句返回的是同一個對象(有助於提高性能,但並發操作同一條數據時,可能不安全),如果設置為false,則相同的sql,后面訪問的是cache的clone副本。
可以在Mapper的具體方法下設置對二級緩存的訪問意願:
-
useCache配置
如果一條語句每次都需要最新的數據,就意味着每次都需要從數據庫中查詢數據,可以把這個屬性設置為false,如:
<select id="selectAll" resultMap="BaseResultMap" useCache="false">
-
刷新緩存(就是清空緩存)
二級緩存默認會在insert、update、delete操作后刷新緩存,可以手動配置不更新緩存,如下:
<update id="updateById" parameterType="User" flushCache="false" />
3、自定義緩存
自定義緩存對象,該對象必須實現 org.apache.ibatis.cache.Cache 接口,如下:
import org.apache.ibatis.cache.Cache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Created by Luky on 2017/10/14. */ public class BatisCache implements Cache { private ReadWriteLock lock = new ReentrantReadWriteLock(); private ConcurrentHashMap<Object,Object> cache = new ConcurrentHashMap<Object, Object>(); private String id; public BatisCache(){ System.out.println("初始化-1!"); } //必須有該構造函數 public BatisCache(String id){ System.out.println("初始化-2!"); this.id = id; } // 獲取緩存編號 public String getId() { System.out.println("得到ID:" + id); return id; } //獲取緩存對象的大小 public int getSize() { System.out.println("獲取緩存大小!"); return 0; } // 保存key值緩存對象 public void putObject(Object key, Object value) { System.out.println("往緩存中添加元素:key=" + key+",value=" + value); cache.put(key,value); } //通過KEY public Object getObject(Object key) { System.out.println("通過kEY獲取值:" + key); System.out.println("OVER"); System.out.println("======================================================="); System.out.println("值為:" + cache.get(key)); System.out.println("=====================OVER=============================="); return cache.get(key); } // 通過key刪除緩存對象 public Object removeObject(Object key) { System.out.println("移除緩存對象:" + key); return null; } // 清空緩存 public void clear() { System.out.println("清除緩存!"); cache.clear(); } // 獲取緩存的讀寫鎖 public ReadWriteLock getReadWriteLock() { System.out.println("獲取鎖對象!!!"); return lock; } }
在Mapper文件里配置使用該自定義的緩存對象,如:
<cache type="com.sanyue.utils.BatisCache"/>
public static void main(String[] args) { SqlSessionFactory factory = SqlSessionFactoryUtil.openSqlSession(); // 獲得SqlSession對象 SqlSession sqlSession = factory.openSession(); // 獲得dao實體 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 進行兩次相同的查詢操作 userMapper.selectByPrimaryKey(1); userMapper.selectByPrimaryKey(1); // 注意,當我們使用二級緩存時候,sqlSession需要使用commit時候才會生效 sqlSession.commit(); System.out.println("\n\n============================================================="); // 獲得一個新的SqlSession 對象 SqlSession sqlSession1 = factory.openSession(); // 進行相同的查詢操作 sqlSession1.getMapper(UserMapper.class).selectByPrimaryKey(1); sqlSession1.commit(); }
日志輸出如下:
初始化-2!
得到ID:com.sanyue.dao.UserMapper
獲取鎖對象!!!
通過kEY獲取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647:
select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值為:null =====================OVER============================== 獲取鎖對象!!! 獲取鎖對象!!! 通過kEY獲取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值為:null =====================OVER============================== 獲取鎖對象!!! 獲取鎖對象!!! 往緩存中添加元素:key=151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1,value=[User{userId=1, loginName='AS-01', password='12121212121', userName='小明', userCode='JSD-009', userType='ADMIN', userActive=true, userPosition='銷售員'}] 獲取鎖對象!!! ============================================================= 獲取鎖對象!!! 通過kEY獲取值:151355725:1423317450:com.sanyue.dao.UserMapper.selectByPrimaryKey:0:2147483647: select user_ID, login_name,user_name, user_code, user_type, user_active, organization_ID,user_position,password from user where user_ID = ? :1 OVER ======================================================= 值為:[User{userId=1, loginName='AS-01', password='12121212121', userName='小明', userCode='JSD-009', userType='ADMIN', userActive=true, userPosition='銷售員'}] =====================OVER============================== 獲取鎖對象!!!
可以看出,每次查詢數據庫前,MyBatis都會先在緩存中查找是否有該緩存對象。只有當調用了commit() 方法,MyBatis才會往緩存中寫入數據,數據記錄的鍵為 數字編號+Mapper名+方法名+SQL語句+參數 格式,值為返回的對象值。
