`
travels_with_you
  • 浏览: 21116 次
  • 性别: Icon_minigender_1
  • 来自: 大连
最近访客 更多访客>>
社区版块
存档分类
最新评论

spring缓存基础知识

阅读更多
   在这里我们使用大家熟悉的EHcache作为缓存方案,首先在配置文件里声明缓存。
roadrantz.-cache.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xmlns:ehcache="http://www.springmodules.org/schema/ehcache"

  xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema.beans/spring-beans-2.0.xsd

      http://www.springmodules.org/schema/ehcache
      http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">

...

</beans>      

加载EHCache配置文件:
<ehcache:config
     configLocation="classpath:ehcache.xml"/>

配置ehcache.xml
<ehcache>
   <defaultCache
       maxElementsInmMemory="500"
       eternel="true"
       overflowToDisk="false"
       memoryStoreEvictionPolicy="LFU" />

   <cache name="rantzCache"
       maxElementsInmMemory="500"
       eternel="true"
       overflowToDisk="false"
       memoryStoreEvictionPolicy="LFU" />
</ehcache>
必须要有一个默认缓存 defaultCache
使用HibernateRantDao的getRantForDay进行缓存
<ehcache:proxy id="rantDao" refId="rantDaoTarget">
    <ehcache:caching methodName="getRantForDay" cacheName="rantzCache" />
</ehcache:proxy>

缓存多个方法,如get..()
    <ehcache:caching methodName="get*" cacheName="rantzCache" />

刷新缓存
  <ehcache:flushing methodName="saveRant" cacheName="rantzCache" when="after"/>

注解驱动缓存,代理多个要缓存的bean
针对java5平台可使用属性@Cacheable @CacheFlush 很便捷的在特定的方法进行声明
@Cacheable(mothodId="rantzCacheModel")
public List<Rant> getRantFotDay(Date day){
   return getHibernateTemplate().find("from " + RANT +"where postedDate = ?",day);
}
@CacheFlush(moothodId="rantzFlushModel")
public void saveRant(Rant rant){
   getHibernateTemplate().saveOrUpdate(rant);
}

rantzCacheModel rantzFlushModel需要配置,在roadrantzcache.xml中
   <ehcache:annotations>
      <ehcache:caching id="rantzCacheModel" cacheName="rantzCache" />
      <ehcache:flushing id="rantzFlushModel" cacheName="rantzCache" when="after" />
   </ehcache:annotations>

一个很简单的缓存流程就完成了。
















3
1
分享到:
评论
5 楼 pastore123 2012-04-03  
可以同时配置spring缓存和hibernate缓存吗?
4 楼 pastore123 2012-04-03  
spring配置的缓存和hibernate配置的二级缓存有什么区别呢?
3 楼 only_java 2009-03-06  
spring in action 2中的实例吧?
2 楼 upheart 2008-12-18  
我觉得讲的灰常好啊,我瞄了一眼就明白了,楼上的是不是理解有问题?
1 楼 exceljava 2008-12-18  
看得有点云里雾里,楼主你自己觉得讲得怎么样?

相关推荐

Global site tag (gtag.js) - Google Analytics