來源:blog.csdn.net/qq_38245668/article/details/105803298
1、MyBatis快取介紹
Mybatis提供對快取的支持,但是在沒有配置的默認情況下,它只開啟一級快取,二級快取需要手動開啟,
一級快取只是相對于同一個SqlSession而言, 也就是針對于同一事務,多次執行同一Mapper的相同查詢方法,第一查詢后,MyBatis會將查詢結果放入快取,在中間不涉及相應Mapper的資料更新(Insert,Update和Delete)操作的情況下,后續的查詢將會從快取中獲取,而不會查詢資料庫,
二級快取是針對于應用級別的快取,也就是針對不同的SqlSession做到快取, 當開啟二級快取時,MyBatis會將首次查詢結果存入對于Mapper的全域快取,如果中間不執行該Mapper的資料更新操作,那么后續的相同查詢都將會從快取中獲取,
2、二級快取問題
根據二級快取的介紹發現,如果Mapper只是單表查詢,并不會出現問題,但是如果Mapper涉及的查詢出現 聯表 查詢,如 UserMapper 在查詢 user 資訊時需要關聯查詢 組織資訊,也就是需要 user 表和 organization 表關聯,OrganizationMapper 在執行更新時并不會更新 UserMapper 的快取,結果會導致在使用相同條件 使用 UserMapper 查詢 user 資訊時,會等到未更新前的 organization 資訊,造成資料不一致的情況,
2.1、資料不一致問題驗證
查詢SQL
SELECT
u.*, o.name org_name
FROM
user u
LEFT JOIN organization o ON u.org_id = o.id
WHERE
u.id = #{userId}
UserMapper
UserInfo queryUserInfo(@Param("userId") String userId);
UserService
public UserEntity queryUser(String userId) {
UserInfo userInfo = userMapper.queryUserInfo(userId);
return userInfo;
}
呼叫查詢,得到查詢結果(多次查詢,得到快取資料),這里 userId = 1,data為user查詢結果
{
"code": "1",
"message": null,
"data": {
"id": "1",
"username": "admin",
"password": "admin",
"orgName": "組織1"
}
}
查詢 對應 organization 資訊,結果
{
"code": "1",
"message": null,
"data": {
"id": "1",
"name": "組織1"
}
}
發現和user快取資料一致,
執行更新 organization 操作,將 組織1 改為 組織2,再次查詢組織資訊
{
"code": "1",
"message": null,
"data": {
"id": "1",
"name": "組織2"
}
}
再次查詢user資訊,發現依舊從快取中獲取
{
"code": "1",
"message": null,
"data": {
"id": "1",
"username": "admin",
"password": "admin",
"orgName": "組織1"
}
}
造成此問題原因為 organization 資料資訊更新只會自己Mapper對應的快取資料,而不會通知到關聯表organization 的一些Mapper更新對應的快取資料,
2.2、問題處理思路
- 在 Mapper1 定義時,手動配置 相應的關聯 Mapper2
- 在 Mapper1 快取 cache1 實體化時,讀取 所關聯的 Mapper2 的快取 cache2相關資訊
- 在 cache1 中存盤 cache2 的參考資訊
- cache1 執行clear時,同步操作 cache2 執行clear
3、關聯快取重繪實作
打開二級快取,本地專案使用 MyBatis Plus
mybatis-plus.configuration.cache-enabled=true
主要用到自定義注解CacheRelations,自定義快取實作RelativeCache和快取背景關系RelativeCacheContext,
注解CacheRelations,使用時需標注在對應mapper上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheRelations {
// from中mapper class對應的快取更新時,需要更新當前注解標注mapper的快取
Class<?>[] from() default {};
// 當前注解標注mapper的快取更新時,需要更新to中mapper class對應的快取
Class<?>[] to() default {};
}
自定義快取RelativeCache實作 MyBatis Cache 介面
public class RelativeCache implements Cache {
private Map<Object, Object> CACHE_MAP = new ConcurrentHashMap<>();
private List<RelativeCache> relations = new ArrayList<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
private String id;
private Class<?> mapperClass;
private boolean clearing;
public RelativeCache(String id) throws Exception {
this.id = id;
this.mapperClass = Class.forName(id);
RelativeCacheContext.putCache(mapperClass, this);
loadRelations();
}
@Override
public String getId() {
return id;
}
@Override
public void putObject(Object key, Object value) {
CACHE_MAP.put(key, value);
}
@Override
public Object getObject(Object key) {
return CACHE_MAP.get(key);
}
@Override
public Object removeObject(Object key) {
return CACHE_MAP.remove(key);
}
@Override
public void clear() {
ReadWriteLock readWriteLock = getReadWriteLock();
Lock lock = readWriteLock.writeLock();
lock.lock();
try {
// 判斷 當前快取是否正在清空,如果正在清空,取消本次操作
// 避免快取出現 回圈 relation,造成遞回無終止,呼叫堆疊溢位
if (clearing) {
return;
}
clearing = true;
try {
CACHE_MAP.clear();
relations.forEach(RelativeCache::clear);
} finally {
clearing = false;
}
} finally {
lock.unlock();
}
}
@Override
public int getSize() {
return CACHE_MAP.size();
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
public void addRelation(RelativeCache relation) {
if (relations.contains(relation)){
return;
}
relations.add(relation);
}
void loadRelations() {
// 加載 其他快取更新時 需要更新此快取的 caches
// 將 此快取 加入至這些 caches 的 relations 中
List<RelativeCache> to = UN_LOAD_TO_RELATIVE_CACHES_MAP.get(mapperClass);
if (to != null) {
to.forEach(relativeCache -> this.addRelation(relativeCache));
}
// 加載 此快取更新時 需要更新的一些快取 caches
// 將這些快取 caches 加入 至 此快取 relations 中
List<RelativeCache> from = UN_LOAD_FROM_RELATIVE_CACHES_MAP.get(mapperClass);
if (from != null) {
from.forEach(relativeCache -> relativeCache.addRelation(this));
}
CacheRelations annotation = AnnotationUtils.findAnnotation(mapperClass, CacheRelations.class);
if (annotation == null) {
return;
}
Class<?>[] toMappers = annotation.to();
Class<?>[] fromMappers = annotation.from();
if (toMappers != null && toMappers.length > 0) {
for (Class c : toMappers) {
RelativeCache relativeCache = MAPPER_CACHE_MAP.get(c);
if (relativeCache != null) {
// 將找到的快取添加到當前快取的relations中
this.addRelation(relativeCache);
} else {
// 如果找不到 to cache,證明to cache還未加載,這時需將對應關系存放到 UN_LOAD_FROM_RELATIVE_CACHES_MAP
// 也就是說 c 對應的 cache 需要 在 當前快取更新時 進行更新
List<RelativeCache> relativeCaches = UN_LOAD_FROM_RELATIVE_CACHES_MAP.putIfAbsent(c, new ArrayList<RelativeCache>());
relativeCaches.add(this);
}
}
}
if (fromMappers != null && fromMappers.length > 0) {
for (Class c : fromMappers) {
RelativeCache relativeCache = MAPPER_CACHE_MAP.get(c);
if (relativeCache != null) {
// 將找到的快取添加到當前快取的relations中
relativeCache.addRelation(this);
} else {
// 如果找不到 from cache,證明from cache還未加載,這時需將對應關系存放到 UN_LOAD_TO_RELATIVE_CACHES_MAP
// 也就是說 c 對應的 cache 更新時需要更新當前快取
List<RelativeCache> relativeCaches = UN_LOAD_TO_RELATIVE_CACHES_MAP.putIfAbsent(c, new ArrayList<RelativeCache>());
relativeCaches.add(this);
}
}
}
}
}
快取背景關系RelativeCacheContext
public class RelativeCacheContext {
// 存盤全量快取的映射關系
public static final Map<Class<?>, RelativeCache> MAPPER_CACHE_MAP = new ConcurrentHashMap<>();
// 存盤 Mapper 對應快取 需要to更新快取,但是此時 Mapper 對應快取還未加載
// 也就是 Class<?> 對應的快取更新時,需要更新 List<RelativeCache> 中的快取
public static final Map<Class<?>, List<RelativeCache>> UN_LOAD_TO_RELATIVE_CACHES_MAP = new ConcurrentHashMap<>();
// 存盤 Mapper 對應快取 需要from更新快取,但是在 加載 Mapper 快取時,這些快取還未加載
// 也就是 List<RelativeCache> 中的快取更新時,需要更新 Class<?> 對應的快取
public static final Map<Class<?>, List<RelativeCache>> UN_LOAD_FROM_RELATIVE_CACHES_MAP = new ConcurrentHashMap<>();
public static void putCache(Class<?> clazz, RelativeCache cache) {
MAPPER_CACHE_MAP.put(clazz, cache);
}
public static void getCache(Class<?> clazz) {
MAPPER_CACHE_MAP.get(clazz);
}
}
使用方式
UserMapper.java
@Repository
@CacheNamespace(implementation = RelativeCache.class, eviction = RelativeCache.class, flushInterval = 30 * 60 * 1000)
@CacheRelations(from = OrganizationMapper.class)
public interface UserMapper extends BaseMapper<UserEntity> {
UserInfo queryUserInfo(@Param("userId") String userId);
}
queryUserInfo是xml實作的介面,所以需要在對應xml中配置<cache-ref namespace=“com.mars.system.dao.UserMapper”/>,不然查詢結果不會被快取化,如果介面為 BaseMapper實作,查詢結果會自動快取化,
UserMapper.xml
<mapper namespace="com.mars.system.dao.UserMapper">
<cache-ref namespace="com.mars.system.dao.UserMapper"/>
<select id="queryUserInfo" resultType="com.mars.system.model.UserInfo">
select u.*, o.name org_name from user u left join organization o on u.org_id = o.id
where u.id = #{userId}
</select>
</mapper>
OrganizationMapper.java
@Repository
@CacheNamespace(implementation = RelativeCache.class, eviction = RelativeCache.class, flushInterval = 30 * 60 * 1000)
public interface OrganizationMapper extends BaseMapper<OrganizationEntity> {
}
CacheNamespace中flushInterval 在默認情況下是無效的,也就是說快取并不會定時清理,ScheduledCache是對flushInterval 功能的實作,MyBatis 的快取體系是用裝飾器進行功能擴展的,所以,如果需要定時重繪,需要使用ScheduledCache給到 RelativeCache添加裝飾,
至此,配置和編碼完成,
開始驗證:
查詢 userId=1的用戶資訊
{
"code":"1",
"message":null,
"data":{
"id":"1",
"username":"admin",
"password":"admin",
"orgName":"組織1"
}
}
更新組織資訊,將 組織1 改為 組織2
{
"code":"1",
"message":null,
"data":{
"id":"1",
"name":"組織2"
}
}
再次查詢用戶資訊
{
"code":"1",
"message":null,
"data":{
"id":"1",
"username":"admin",
"password":"admin",
"orgName":"組織2"
}
}
符合預期,
近期熱文推薦:
1.1,000+ 道 Java面試題及答案整理(2022最新版)
2.勁爆!Java 協程要來了,,,
3.Spring Boot 2.x 教程,太全了!
4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這才是優雅的方式!!
5.《Java開發手冊(嵩山版)》最新發布,速速下載!
覺得不錯,別忘了隨手點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/472849.html
標籤:Java
上一篇:Spring 原始碼(13)Spring Bean 的創建程序(4)
下一篇:Maven常用命令
