ibatis cache使用

转自:http://kill8108.blog.163.com/blog/static/43419968200861835828417/

IBATIS是针对数据作缓存的(若缓存对象,那些对象必实现了Serializable接口),为了避免每次查库,这里会有数据同步问题了;

使用缓存两个注意点:

1、在sqlMapConfig.xml的配置;

2、缓存中的对象(你想查询的pojo),必实现Serializable;

 

 

1、基本配置:

在sqlMapConfig.xml中配置:(使用缓存必设以下属性)

    <settings

扫描二维码关注公众号,回复: 399757 查看本文章

       cacheModelsEnabled="true"

       enhancementEnabled="true"

lazyLoadingEnabled="true"/>

 

在sqlMap中加入

 

<cacheModel

id="product-cache"//唯一

type ="LRU"//缓存类别

readOnly="true"//是否更新,true当数据对象更新了,那从缓存中删除,下次访问重新加载,看具体情况,当经常更新时选false,反之为true,为true时,缓存最好,但若有更新数据的需要为false,不写默认为true

serialize="false">//解决多线程(多个session)问题,true时分为全局与局部之分,false只有局部,局部对性能提升有限,一般使用true,不写默认为false

</cacheModel>

 

 

<!—Statement配置-->

<select id="getUser"

parameterClass="java.lang.String"

resultClass="user"

cacheModel="product-cache"//指定使用什么样的缓存

<![CDATA[

select

name,

sex

from t_user

where name = #name#

]]>

</select>

 

2、参数说明:type有:缓存类型,有MEMORY,LRU,FIFO,OSCACHE这几种,以下有将对每一种作说明;

 

Momory的配置:

<cacheModel id="user_cache" type="MEMORY">

<flushInterval hours="24"/>//多少时间清掉缓存(minutes)

<flushOnExecute statement="updateUser"/>//定义运行了那个statement刷新缓存,这里注意了,若有其它更新方式(底层),那缓存不会更新

<property name="reference-type" value="WEAK" />//指定Momory缓存时,使用什么缓存基志

</cacheModel>

 

 

MEMORY:与JAVA中的对象引用有很大的关系,基本上就是这种引用(strong,soft,weak),建议使用weak/soft;soft将在内存不足回收,weak每次回收器回收都回收;

 

LRU配置:当Cache达到预先设定的最大容量时,ibatis会按照“最少使用”原则将使用频率最少的对象从缓冲中清除。

 

<cacheModel id="userCache" type="LRU">

<flushInterval hours="24"/>与momory相同

<flushOnExecute statement="updateUser"/>//与momory相同

<property name="size" value="1000" />//Cache的最大容量

</cacheModel>

 

 

FIFO:先进先出型缓存,最先放入Cache中的数据将被最先废除。可配置参数与LRU型相同

<cacheModel id="userCache" type="FIFO">

<flushInterval hours="24"/>

<flushOnExecute statement="updateUser"/>

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

</cacheModel>

 

 

OSCache:与上面几种类型的Cache不同,OSCache来自第三方组织Opensymphony;

<cacheModel id="userCache" type="OSCACHE">

<flushInterval hours="24"/>

<flushOnExecute statement="updateUser"/>

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

</cacheModel>

 

根据ibatis开发指南里,建议使用OSCache,这种可以实现集群方式的缓存,更高效的设计;

 

 

iBATIS使用缓存(oscache)测试

 

1、  测试机器:

硬件:

IBM本本,2G内存,VISTA的32位系统,双核CPU

软件:

数据库为mysql6.0,单表,数据量为1539200条记录

 

2、  测试结果,

 

是否缓存

 

第一页

 

跳到1000页

 

返回第一页

 

再返回1000页

 

跳到2000页

 

返回1000页

 

再返回2000页

 

 

33

 

 

 

153

 

 

 

8

 

 

 

106

 

 

 

132

 

 

 

117

 

 

150

 

 

 

 

59

 

152

 

10

 

1

 

105

 

3

 

1

 

结果

 

第一次查询有缓存的多26

 

第一次查询,有缓存少1

 

返回第一页缓存的多2

 

再返回1000时,缓存只需要1

 

跳到2000,缓存的少27

 

再返回1000,缓存的少114

 

再返回2000,有缓存的只需要1

 

 

 

 

 

注:以上单位都是ms,并且从查询日志中看到有缓存的真的没有查库了;

 

猜你喜欢

转载自lf6627926.iteye.com/blog/2023513
今日推荐