您的位置:首页 > 编程语言 > Java开发

ibatis 实现cache 注解+cacheModel实现

2017-08-29 15:16 447 查看
  一、使用cacheModel 在sqlMap中直接标注哪个方法需要配置缓存
  二、使用bean的方式 通过@Cacheable注解标注对应的cache

cacheModel 相关属性

type 取值类型:

◆"MEMORY” (com.ibatis.db.sqlmap.cache.memory.MemoryCacheController) 。MEMORY cache 实现使用 reference 类型来管理 cache 的行为。垃圾收集器可以根据 reference类型判断是否要回收 cache 中的数据。MEMORY实现适用于没有统一的对象重用模式的应用,或内存不足的应用。

◆“LRU” (com.ibatis.db.sqlmap.cache.lru.LruCacheController) 。LRU Cache 实现用“近期最少使用”原则来确定如何从 Cache 中清除对象。当 Cache溢出时,最近最少使用的对象将被从 Cache 中清除。使用这种方法,如果一个特定的对象总是被使用,它将保留在 Cache 中,而且被清除的可能性最小。对于在较长的期间内,某些用户经常使用某些特定对象的情况(例如,在 PaginatedList 和常用的查询关键字结果集中翻页) ,LRU Cache
是一个不错的选择。

◆“FIFO” (com.ibatis.db.sqlmap.cache.fifo.FifoCacheController) 。FIFO Cache 实现用“先进先出”原则来确定如何从 Cache 中清除对象。当 Cache 溢出时,最先进入 Cache 的对象将从 Cache 中清除。对于短时间内持续引用特定的查询而后很可能不再使用的情况,FIFO Cache 是很好的选择。

◆“OSCACHE” (com.ibatis.db.sqlmap.cache.oscache.OSCacheController)  。OSCACHE Cache 实现是OSCache2.0缓存引擎的一个 Plugin。它具有高度的可配置性,分布式,高度的灵活性。

其他属性:
◆ serialize:只有在readOnly为false的情况下才生效,因为在readOnly为true时,所有数据对象相同,只有可读写时,才会出现不同的session拥有不同的数据对象副本。

◆ flushInterval:指定缓存自动刷新的时间,可以为hours,minutes,seconds,milliseconds.

◆ flushOnExecute:指定在发生哪些操作时,更新缓存。

◆ property:不同type的cachemodel有不同的属性。

  一、使用cacheModel 在sqlMap中直接标注哪个方法需要配置缓存
这里加上Cowboys namespace 是因为核心配置sql-map中配置了useStatementNamespaces="true"。

     <cacheModel id="ehCache" type="LRU" readOnly="true"
           serialize="true">
           <flushInterval hours="24" />
           <flushOnExecute statement="Cowboys.getById" />
           <property value="500" name="size" />
     </cacheModel>
------------------------------------------------------------------------
<select id="getById" resultMap="cowboysResultMap" cacheModel="ehCache">
           select
           <include refid="commonColumns" />
        <![CDATA[
             from t_dat_dict
             where
                   data_cd = #id#
         ]]>
     </select>

sql-map.xml

<sqlMapConfig>
     <settings cacheModelsEnabled="true" lazyLoadingEnabled="true"
           enhancementEnabled="true" maxSessions="128" maxTransactions="50"
           maxRequests="512" useStatementNamespaces="true" />
     <!-- 这里无需配置sqlMap,可以通过spring的配置加载某个目录的多个SqlMap.xml -->
     <sqlMap resource="/net/spring/entity/sqlMap/CowboysSqlMap.xml" />
</sqlMapConfig>

测试结果:

2017-08-22 16:22:06,506 耗时:182090 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:DispatcherServlet with name 'spring' processing GET request for [/SpringMvcVsRestVsThreadpool/rest/cowboys/v2/4782]]
2017-08-22 16:22:06,506 耗时:182090 [日志来自:.annotation.RequestMappingHandlerMapping 日志类型: DEBUG 日志内容:Looking up handler method for path /cowboys/v2/4782]
2017-08-22 16:22:06,512 耗时:182096 [日志来自:.annotation.RequestMappingHandlerMapping 日志类型: DEBUG 日志内容:Returning handler method [public net.spring.entity.Cowboys net.spring.controller.CowboysController.getOne(java.lang.String)]]
2017-08-22 16:22:06,512 耗时:182096 [日志来自:ctory.support.DefaultListableBeanFactory 日志类型
4000
: DEBUG 日志内容:Returning cached instance of singleton bean 'cowboysController']
2017-08-22 16:22:06,513 耗时:182097 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Last-Modified value for [/SpringMvcVsRestVsThreadpool/rest/cowboys/v2/4782] is: -1]
2017-08-22 16:22:06,538 耗时:182122 [日志来自:orm.ibatis.SqlMapClientTemplate          日志类型: DEBUG 日志内容:Opened SqlMapSession [com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl@1db7bce] for iBATIS operation]
2017-08-22 16:22:06,546 耗时:182130 [日志来自:jdbc.datasource.DataSourceUtils          日志类型: DEBUG 日志内容:Fetching JDBC Connection from DataSource]
2017-08-22 16:22:06,945 耗时:182529 [日志来自:java.sql.Connection                      日志类型: DEBUG 日志内容:{conn-100000} Connection]
2017-08-22 16:22:06,949 耗时:182533 [日志来自:orm.ibatis.SqlMapClientTemplate          日志类型: DEBUG 日志内容:Obtained JDBC Connection [jdbc:oracle:thin:@192.168.70.102:1521:ora11gR2, UserName=INTER, Oracle JDBC driver] for iBATIS operation]
2017-08-22 16:22:06,949 耗时:182533 [日志来自:engine.cache.CacheModel                  日志类型: DEBUG 日志内容:Cache 'Cowboys.ehCache': cache miss]
2017-08-22 16:22:06,952 耗时:182536 [日志来自:java.sql.Connection                      日志类型: DEBUG 日志内容:{conn-100000} Preparing Statement:    select          data_cd ,          data_nm ,          data_type ,         
data_kind                               from t_dat_dict          where           data_cd = ?    
     ]
2017-08-22 16:22:07,065 耗时:182649 [日志来自:java.sql.PreparedStatement               日志类型: DEBUG 日志内容:{pstm-100001} Executing Statement:    select          data_cd ,          data_nm ,          data_type ,          data_kind                               from
t_dat_dict          where           data_cd = ?         ]
2017-08-22 16:22:07,065 耗时:182649 [日志来自:java.sql.PreparedStatement               日志类型: DEBUG 日志内容:{pstm-100001} Parameters: [4782]]
2017-08-22 16:22:07,065 耗时:182649 [日志来自:java.sql.PreparedStatement               日志类型: DEBUG 日志内容:{pstm-100001} Types: [java.lang.String]]
2017-08-22 16:22:07,094 耗时:182678 [日志来自:java.sql.ResultSet                       日志类型: DEBUG 日志内容:{rset-100002} ResultSet]
2017-08-22 16:22:07,109 耗时:182693 [日志来自:java.sql.ResultSet                       日志类型: DEBUG 日志内容:{rset-100002} Header: [data_cd, data_nm, data_type, data_kind]]
2017-08-22 16:22:07,109 耗时:182693 [日志来自:java.sql.ResultSet                       日志类型: DEBUG 日志内容:{rset-100002} Result: [4782, 过桥费, 0001, 0]]
2017-08-22 16:22:07,112 耗时:182696 [日志来自:engine.cache.CacheModel                  日志类型: DEBUG 日志内容:Cache 'Cowboys.ehCache': flushed]
2017-08-22 16:22:07,112 耗时:182696 [日志来自:engine.cache.CacheModel                  日志类型: DEBUG 日志内容:Cache 'Cowboys.ehCache': stored object '[Cowboys [id=4782, name=过桥费, age=0001, level=0]]']
2017-08-22 16:22:07,112 耗时:182696 [日志来自:jdbc.datasource.DataSourceUtils          日志类型: DEBUG 日志内容:Returning JDBC Connection to DataSource]
2017-08-22 16:22:07,176 耗时:182760 [日志来自:ation.RequestResponseBodyMethodProcessor 日志类型: DEBUG 日志内容:Written [Cowboys [id=4782, name=过桥费, age=0001, level=0]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@8b85eb]]
2017-08-22 16:22:07,177 耗时:182761 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Null ModelAndView returned to DispatcherServlet with name 'spring': assuming HandlerAdapter completed request handling]
2017-08-22 16:22:07,178 耗时:182762 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Successfully completed request]
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2017-08-22 16:22:18,500 耗时:194084 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:DispatcherServlet with name 'spring' processing GET request for [/SpringMvcVsRestVsThreadpool/rest/cowboys/v2/4782]]
2017-08-22 16:22:18,500 耗时:194084 [日志来自:.annotation.RequestMappingHandlerMapping 日志类型: DEBUG 日志内容:Looking up handler method for path /cowboys/v2/4782]
2017-08-22 16:22:18,502 耗时:194086 [日志来自:.annotation.RequestMappingHandlerMapping 日志类型: DEBUG 日志内容:Returning handler method [public net.spring.entity.Cowboys net.spring.controller.CowboysController.getOne(java.lang.String)]]
2017-08-22 16:22:18,502 耗时:194086 [日志来自:ctory.support.DefaultListableBeanFactory 日志类型: DEBUG 日志内容:Returning cached instance of singleton bean 'cowboysController']
2017-08-22 16:22:18,502 耗时:194086 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Last-Modified value for [/SpringMvcVsRestVsThreadpool/rest/cowboys/v2/4782] is: -1]
2017-08-22 16:22:18,503 耗时:194087 [日志来自:orm.ibatis.SqlMapClientTemplate          日志类型: DEBUG 日志内容:Opened SqlMapSession [com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl@44fa35] for iBATIS operation]
2017-08-22 16:22:18,503 耗时:194087 [日志来自:jdbc.datasource.DataSourceUtils          日志类型: DEBUG 日志内容:Fetching JDBC Connection from DataSource]
2017-08-22 16:22:18,508 耗时:194092 [日志来自:java.sql.Connection                      日志类型: DEBUG 日志内容:{conn-100003} Connection]
2017-08-22 16:22:18,512 耗时:194096 [日志来自:orm.ibatis.SqlMapClientTemplate          日志类型: DEBUG 日志内容:Obtained JDBC Connection [jdbc:oracle:thin:@192.168.70.102:1521:ora11gR2, UserName=INTER, Oracle JDBC driver] for iBATIS operation]
2017-08-22 16:22:18,512 耗时:194096 [日志来自:engine.cache.CacheModel                  日志类型: DEBUG 日志内容:Cache 'Cowboys.ehCache': retrieved object '[Cowboys [id=4782, name=过桥费, age=0001, level=0]]']
2017-08-22 16:22:18,513 耗时:194097 [日志来自:jdbc.datasource.DataSourceUtils          日志类型: DEBUG 日志内容:Returning JDBC Connection to DataSource]
2017-08-22 16:22:18,515 耗时:194099 [日志来自:ation.RequestResponseBodyMethodProcessor 日志类型: DEBUG 日志内容:Written [Cowboys [id=4782, name=过桥费, age=0001, level=0]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@8b85eb]]
2017-08-22 16:22:18,515 耗时:194099 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Null ModelAndView returned to DispatcherServlet with name 'spring': assuming HandlerAdapter completed request handling]
2017-08-22 16:22:18,516 耗时:194100 [日志来自:web.servlet.DispatcherServlet            日志类型: DEBUG 日志内容:Successfully completed request]

通过日志可以看出第一遍取自数据库,第二遍从缓存中获取!
---------------------------------------------------------------------------------------------------------------------------------------
二、通过bean注入+注解方式实现

bean配置xml文件:

<cache:annotation-driven cache-manager="cacheManager" />
     <!--声明一个缓存管理器(EhCacheCacheManager) 这里的实现代码是通过传入EhCache的CacheManager实例实现的 -->
     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
           <property name="cacheManager" ref="ehcache"></property>
     </bean>

     <bean id="ehcache"
          class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
           <!-- 指定 ehcache配置文件路径 -->
           <property name="configLocation" value="/WEB-INF/ehcache.xml"></property>
     </bean>

ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
     <diskStore path="java.io.tmpdir" />
     <!-- 多主机负载时,使用EhCache RMI方式的分布式缓存。见build/prod目录下每个节点的配置。 -->
     <!-- DefaultCache setting. -->
     <defaultCache maxElementsInMemory="10000"
           memoryStoreEvictionPolicy="LRU" eternal="false" timeToIdleSeconds="300"
           timeToLiveSeconds="300" overflowToDisk="false" diskPersistent="false" />
     <cache name="myCache" overflowToDisk="false" eternal="true"
           diskPersistent="false" maxElementsInMemory="10000"
           memoryStoreEvictionPolicy="LRU" />
</ehcache>

 controller类使用cacheable注解绑定myCache:   

 @Cacheable(value = { "myCache" })
     @GET
     @RequestMapping(value = "/v2/{id}", method = RequestMethod.GET)
     public @ResponseBody Cowboys getOne(@PathVariable("id") String key) {
           Map<String, String> condition = new HashMap<String, String>();
           condition.put("id", key);
           return cowboysDao.getById(condition);
     }

最终结果与第一种一致。

http://blog.csdn.net/xusongsong520/article/details/8240717
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ibatis spring