Cacheのタイプ(MEMORY,FIFO,LRUなど)
iBATISで利用できるキャッシュの実装(キャッシュタイプ)には、以下の4種類があります。
- MEMORY(com.ibatis.db.sqlmap.cache.memory.MemoryCacheController)
- FIFO (com.ibatis.db.sqlmap.cache.fifo.FifoCacheController)
- LRU(com.ibatis.db.sqlmap.cache.lru.LruCacheController)
- OSCACHE (com.ibatis.db.sqlmap.cache.oscache.OSCacheController)
上記に加えて、com.ibatis.sqlmap.engine.cache.CacheControllerインターフェースを実装すれば、独自のキャッシュタイプを作成できるようです。
MEMORY
キャッシュされているオブジェクトの解放をJVMにゆだねる方式。reference-typeの指定に従って、JVMがオブジェクトを解放します。
<cacheModel id="product-cache" type="MEMORY"> <flushInterval hours="24"/> <flushOnExecute statement="insertProduct"/> <flushOnExecute statement="updateProduct"/> <flushOnExecute statement="deleteProduct"/> <property name="reference-type" value="WEAK" /> </cacheModel>
【適しているケース】
- オブジェクトを再利用するパターンを特定できない場合
- 大量のメモリが使えない場合
reference-typeで指定可能な値は、JVMのreference typesに対応します(java.lang.refの“reachability"を参照)。
- WEAK(デフォルト)
- SOFT
- STRONG
- time-intervalまたはflushOnExecuteで明示的にFlushしない限り、メモリにキャッシュされることが保証されます。
reference-type | 利点・欠点 | 適するケース |
---|---|---|
WEAK | ほとんどの場合に適合する(らしい。) | |
SOFT | ?? | |
STRONG |
FIFO
キャッシュが一杯になった場合に、First In First Outアルゴリズムでオブジェクトをキャッシュから削除します。
<cacheModel id="product-cache" type="FIFO"> <flushInterval hours="24"/> <flushOnExecute statement="insertProduct"/> <flushOnExecute statement="updateProduct"/> <flushOnExecute statement="deleteProduct"/> <property name="size" value="1000" /> </cacheModel>
【適しているケース】
- 何度か連続して参照されるが、後からは参照しないクエリパターンを使う場合(ってケースが想像できないんですけど。)
【留意点】
- 多くキャッシュしすぎるとOut Of Memoryが発生するリスクがある。
LRU
キャッシュが一杯になった場合に、Least Recently Usedアルゴリズムでオブジェクトをキャッシュから削除します。
【適しているケース】
- 長期にわたってオブジェクトが頻繁に利用されるパターンがある場合
【留意点】
- 多くキャッシュしすぎるとOut Of Memoryが発生するリスクがある。
<cacheModel id="product-cache" type="LRU"> <flushInterval hours="24"/> <flushOnExecute statement="insertProduct"/> <flushOnExecute statement="updateProduct"/> <flushOnExecute statement="deleteProduct"/> <property name="size" value="1000" /> </cacheModel>
OSCACHE
OSCache 2.0エンジンを利用するためのプラグイン。
<cacheModel id="product-cache" type="OSCACHE"> <flushInterval hours="24"/> <flushOnExecute statement="insertProduct"/> <flushOnExecute statement="updateProduct"/> <flushOnExecute statement="deleteProduct"/> </cacheModel>
キャッシュ設定はcacheModel要素ではなく、oscache.propertiesに行います。このファイルはクラスパスのルートに配置します。
参考
- 「iBATIS Data Mapper Developer Guide」- 「Caching Mapped Statement Results」