J2SE Java基础 J2EE 设计模式 struts hibernate spring freemarker ibatis xml xslt Javascript mysql Linux 系统架构
Java高级 webwork webservice 网页制作 oracle sql server 数据库基础 软件工程 网站建设 SEO 黑客基础 名人堂 Ruby
首页 > 技术文档 > Java > J2EE > 利用 Spring 和 EHCache 缓存结果

利用 Spring 和 EHCache 缓存结果

作者:  来源: csdn  标签:xml ehcache hibernate (English)
利用 Spring IoC 配置 EHCache
  1.   
  2. <ehcache>  
  3.   
  4.     
  5.   
  6.          如果该路径是 Java 系统参数,当前虚拟机会重新赋值。   
  7.   
  8.          下面的参数这样解释:   
  9.          user.home – 用户主目录   
  10.          user.dir      – 用户当前工作目录   
  11.          java.io.tmpdir – 默认临时文件路径 -->  
  12.     <diskStore path="java.io.tmpdir"/>  
  13.   
  14.   
  15.     
  16.   
  17.         下列属性是 defaultCache 必须的:   
  18.   
  19.         maxInMemory           - 设定内存中创建对象的最大值。   
  20.         eternal                        - 设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超   
  21.                                               时限制且元素永不消亡。   
  22.         timeToIdleSeconds  - 设置某个元素消亡前的停顿时间。   
  23.                                               也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。   
  24.                                               这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则   
  25.                                               设置该属性也无用)。   
  26.                                               如果该值是 0 就意味着元素可以停顿无穷长的时间。   
  27.         timeToLiveSeconds - 为元素设置消亡前的生存时间。   
  28.                                                也就是一个元素从构建到消亡的最大时间间隔值。   
  29.                                                这只能在元素不是永久驻留时有效。   
  30.         overflowToDisk        - 设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘   
  31.                                                上。   
  32.         -->  
  33.   
  34.     <cache name="org.taha.cache.METHOD_CACHE"  
  35.         maxElementsInMemory="300"  
  36.         eternal="false"  
  37.         timeToIdleSeconds="500"  
  38.         timeToLiveSeconds="500"  
  39.         overflowToDisk="true"  
  40.         />  
  41. ehcache>  
拦截器将使用 ”org.taha.cache.METHOD_CACHE” 区域缓存方法返回结果。下面利用 Spring IoC 让 bean 来访问这一区域。
 
 
  1.   
  2.   
  3.   
  4. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  5.   <property name="configLocation">  
  6.     <value>classpath:ehcache.xmlvalue>  
  7.   property>  
  8. bean>  
  9.   
  10. <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">  
  11.   <property name="cacheManager">  
  12.     <ref local="cacheManager"/>  
  13.   property>  
  14.   <property name="cacheName">  
  15.     <value>org.taha.cache.METHOD_CACHEvalue>  
  16.   property>  
  17. bean>  

构建我们的 MethodCacheInterceptor

该拦截器实现org.aopalliance.intercept.MethodInterceptor接口。一旦运行起来(kicks-in),它首先检查被拦截方法是否被配置为可缓存的。这将可选择性的配置想要缓存的 bean 方法。只要调用的方法配置为可缓存,拦截器将为该方法生成 cache key 并检查该方法返回的结果是否已缓存。如果已缓存,就返回缓存的结果,否则再次调用被拦截方法,并缓存结果供下次调用。

  1.   
  2. /*  
  3.  * Copyright 2002-2004 the original author or authors.  
  4.  *  
  5.  * Licensed under the Apache License, Version 2.0 (the "License");  
  6.  * you may not use this file except in compliance with the License.  
  7.  * You may obtain a copy of the License at  
  8.  *  
  9.  *      http://www.apache.org/licenses/LICENSE-2.0  
  10.  *  
  11.  * Unless required by applicable law or agreed to in writing, software  
  12.  * distributed under the License is distributed on an "AS IS" BASIS,  
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  14.  * See the License for the specific language governing permissions and  
  15.  * limitations under the License.  
  16.  */  
  17.   
  18. package org.taha.interceptor;   
  19.   
  20. import java.io.Serializable;   
  21.   
  22. import org.aopalliance.intercept.MethodInterceptor;   
  23. import org.aopalliance.intercept.MethodInvocation;   
  24.   
  25. import org.apache.commons.logging.LogFactory;   
  26. import org.apache.commons.logging.Log;   
  27.   
  28. import org.springframework.beans.factory.InitializingBean;   
  29. import org.springframework.util.Assert;   
  30.   
  31. import net.sf.ehcache.Cache;   
  32. import net.sf.ehcache.Element;   
  33.   
  34. /**  
  35.  * @author  
  36.  * @since 2004.10.07  
  37.  */  
  38. public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean {   
  39.   private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);   
  40.   
  41.   private Cache cache;   
  42.   
  43.   /**  
  44.    * 设置缓存名  
  45.    */  
  46.   public void setCache(Cache cache) {   
  47.     this.cache = cache;   
  48.   }   
  49.   
  50.   /**  
  51.    * 检查是否提供必要参数。  
  52.    */  
  53.   public void afterPropertiesSet() throws Exception {   
  54.     Assert.notNull(cache, "A cache is required. Use setCache(Cache) to provide one.");   
  55.   }   
  56.   
  57.   /**  
  58.    * 主方法  
  59.    * 如果某方法可被缓存就缓存其结果  
  60.    * 方法结果必须是可序列化的(serializable)  
  61.    */  
  62.   public Object invoke(MethodInvocation invocation) throws Throwable {   
  63.     String targetName  = invocation.getThis().getClass().getName();   
  64.     String methodName  = invocation.getMethod().getName();   
  65.     Object[] arguments = invocation.getArguments();   
  66.     Object result;   
  67.   
  68.     logger.debug("looking for method result in cache");   
  69.     String cacheKey = getCacheKey(targetName, methodName, arguments);   
  70.     Element element = cache.get(cacheKey);   
  71.     if (element == null) {   
  72.       //call target/sub-interceptor   
  73.       logger.debug("calling intercepted method");   
  74.       result = invocation.proceed();   
  75.   
  76.       //cache method result   
  77.       logger.debug("caching result");   
  78.       element = new Element(cacheKey, (Serializable) result);   
  79.       cache.put(element);   
  80.     }   
  81.     return element.getValue();   
  82.   }   
  83.   
  84.   /**  
  85.    * creates cache key: targetName.methodName.argument0.argument1...  
  86.    */  
  87.   private String getCacheKey(String targetName,   
  88.                              String methodName,   
  89.                              Object[] arguments) {   
  90.     StringBuffer sb = new StringBuffer();   
  91.     sb.append(targetName)   
  92.       .append(".").append(methodName);   
  93.     if ((arguments != null) && (arguments.length != 0)) {   
  94.       for (int i=0; i
  95.         sb.append(".")   
  96.           .append(arguments[i]);   
  97.       }   
  98.     }   
  99.   
  100.     return sb.toString();   
  101.   }   
  102. }  

MethodCacheInterceptor 代码说明了:

  • 默认条件下,所有方法返回结果都被缓存了(methodNames null
  • 缓存区利用 IoC 形成
  • cacheKey 的生成还包括方法参数的因素(译注:参数的改变会影响 cacheKey

使用 MethodCacheInterceptor

下面摘录了怎样配置 MethodCacheInterceptor:

  1.   
  2. <bean id="methodCacheInterceptor" class="org.taha.interceptor.MethodCacheInterceptor">  
  3.   <property name="cache">  
  4.     <ref local="methodCache" />  
  5.   property>  
  6. bean>  
  7.   
  8. <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  
  9.   <property name="advice">  
  10.     <ref local="methodCacheInterceptor"/>  
  11.   property>  
  12.   <property name="patterns">  
  13.     <list>  
  14.       <value>.*methodOnevalue>  
  15.       <value>.*methodTwovalue>  
  16.     list>  
  17.   property>  
  18. bean>  
  19.   
  20. <bean id="myBean" class="org.springframework.aop.framework.ProxyFactoryBean">  
  21.   <property name="target">  
  22.    <bean class="org.taha.beans.MyBean"/>  
  23.   property>  
  24.   <property name="interceptorNames">  
  25.     <list>  
  26.       <value>methodCachePointCutvalue>  
  27.     list>  
  28.   property>  
  29. bean>  

译注

夏昕所著《Hibernate 开发指南》,其中他这样描述 EHCache 配置文件的:

  1.   
  2. <ehcache>  
  3.     <diskStore path="java.io.tmpdir"/>  
  4.     <defaultCache  
  5.         maxElementsInMemory="10000" //Cache中最大允许保存的数据数量   
  6.         eternal="false"                       //Cache中数据是否为常量   
  7.         timeToIdleSeconds="120"     //缓存数据钝化时间   
  8.         timeToLiveSeconds="120"     //缓存数据的生存时间   
  9.         overflowToDisk="true"       //内存不足时,是否启用磁盘缓存   
  10.     />  
  11. ehcache>  
    在 Spring 里配置 EHCache 很简单。你只需一个 ehcache.xml 文件,该文件用于配置 EHCache:

相关文章
(2007年07月31日)基于 J2EE 体系实现多层结构 Blog 平台
(2007年11月14日)使用ehcache

评论列表

发表评论

赞助商