IBatis 的快取機制

2021-08-31 02:20:32 字數 2132 閱讀 9888

快取機制,也是基於 key-value 的方式,確定了 key 的來龍去脈能很好的認識快取的生存週期。

從配置檔案解析說起:

0 1 private errorcontext errorcontext;

0 2    private cachemodel cachemodel;

0 3

0 4      cachemodelconfig(sqlmapconfiguration config, string id, cachecontroller controller, boolean readonly, boolean serialize) ... catch (exception e) ...

20   errorcontext.setmoreinfo("check the cache model configuration." );

21 if (client.getdelegate().iscachemodelsenabled()) ...

24   errorcontext.setmoreinfo(null );

25   errorcontext.setobjectid(null );

26   }

注意紅色的**,再來看看 cachemodel,如下:

1  public class cachemodel implements executelistener

executelistener 是乙個***,它在 update、insert,delete 操作執行後,觸發些事件:源頭如下:

public inte***ce cachecontroller

實現以下幾種:

fifocachecontroller

lrucachecontroller

memorycachecontroller

oscachecontroller

再看看具體的實現,如memorycachecontroller的:

private map cache = collections.synchronizedmap(new hashmap());

1  public void flush(cachemodel cachemodel)

其它的幾種實現,也基本大致如此,不在具體貼**了。

從上面的**分析可以看出 ibatis 的快取的更新機制大概如下:

執行 update,insert,delete 等操作時,觸發對應的事件,註冊的事件響應此操作,根據xml配置的快取,對其資料做清空操作,也就是這個快取中的資料全部清空,而不是

清空某乙個 key對應的值,即如我更新了乙個 id= 5 的資料,則這個快取中的資料全部將清空。這樣倒很簡單也很徹底,由此帶來的問題就很多了,如果你的 update 等相關的操作太頻繁了,這裡的快取則失去意義,且加大了系統本身的開銷。因此,我認為對於更新不是很頻繁的資料可以用 ibatis 自身的快取機制,如果是很頻繁的資料就不要使用 ibatis 自身的快取。舉例說明:

< cachemodel id ="product-cache" imlementation ="lru" > 

< flushinterval hours ="24" />

< flushonexecute statement ="insertproduct" /> 

< flushonexecute statement ="updateproduct" />

< flushonexecute statement ="deleteproduct" /> 

< property name ="size" value ="1000" /> 

< statement id ="getproductlist" parameterclass ="int" cachemodel ="product-cache" > 

select * from product where prd_cat_id = #value# 

如果你配置了以上操作,如果做了  insert_product,updateproduct,deleteproduct 中的任何乙個操作,都將清空快取 product-cache 中的所有資料,也就是 getproductlist 方法將執行資料庫操作,不能從快取中獲取資料。

最後一句,大家不要對 ibatis 的快取抱太大的希望,雖然我們的系統中使用的是 ibatis

Ibatis快取設定

cachemodel id cache logic columns type memory readonly true serialize false flushinterval hours 24 property name reference type value strong cachemode...

ibatis的快取中計算cachekey的過程

cachingstatement在執行查詢的時候,會先從cachemodel中獲取結果。如果結果為空,則執行查詢並將結果儲存在cachemodel中。在讀寫cachemodel的過程中,都需要獲得cachekey物件,以cachekey作為快取的key。下面是獲得cachekey的過程 cachin...

Ibatis輸出結果快取元素

摘自 先看乙個例項 3個屬性 1 type指定使用 近期最少使用 lru 實現。2 屬性readonly如果不寫,預設是true,這時的快取效果無疑最好,因為系統不需要考慮更新操作引起快取與實際資料不一致的問題,唯讀快取的例子是固化到資料庫中的一些配置參數列。但是,通常我們想快取的資料是需要增刪改的...