Encache的使用与说明

来源:互联网 发布:603636南威软件 编辑:程序博客网 时间:2024/05/30 02:23

 导言

从 Spring 1.1.1 开始,EHCache 就作为一种通用缓存解决方案集成进 Spring。

我将示范拦截器的例子,它能把方法返回的结果缓存起来。

 

利用 Spring IoC 配置 EHCache

在 Spring 里配置 EHCache 很简单。你只需一个 ehcache.xml 文件,该文件用于配置 EHCache:

  1. <ehcache>
  2.     <!—设置缓存文件 .data 的创建路径。
  3.          如果该路径是 Java 系统参数,当前虚拟机会重新赋值。
  4.          下面的参数这样解释:
  5.          user.home – 用户主目录
  6.          user.dir      – 用户当前工作目录
  7.          java.io.tmpdir – 默认临时文件路径 -->
  8.     <diskStore path="java.io.tmpdir"/>
  9.     <!—缺省缓存配置。CacheManager 会把这些配置应用到程序中。
  10.         下列属性是 defaultCache 必须的:
  11.         maxInMemory           - 设定内存中创建对象的最大值。
  12.         eternal                        - 设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超
  13.                                               时限制且元素永不消亡。
  14.         timeToIdleSeconds  - 设置某个元素消亡前的停顿时间。
  15.                                               也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。
  16.                                               这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则
  17.                                               设置该属性也无用)。
  18.                                               如果该值是 0 就意味着元素可以停顿无穷长的时间。
  19.         timeToLiveSeconds - 为元素设置消亡前的生存时间。
  20.                                                也就是一个元素从构建到消亡的最大时间间隔值。
  21.                                                这只能在元素不是永久驻留时有效。
  22.         overflowToDisk        - 设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘
  23.                                                上。
  24.         -->
  25.     <cache name="org.taha.cache.METHOD_CACHE"
  26.         maxElementsInMemory="300"
  27.         eternal="false"
  28.         timeToIdleSeconds="500"
  29.         timeToLiveSeconds="500"
  30.         overflowToDisk="true"
  31.         />
  32. </ehcache>

拦截器将使用 ”org.taha.cache.METHOD_CACHE” 区域缓存方法返回结果。下面利用 Spring IoC 让 bean 来访问这一区域。

  1. <!-- ======================   缓存   ======================= -->
  2. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  3.   <property name="configLocation">
  4.     <value>classpath:ehcache.xml</value>
  5.   </property>
  6. </bean>
  7. <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
  8.   <property name="cacheManager">
  9.     <ref local="cacheManager"/>
  10.   </property>
  11.   <property name="cacheName">
  12.     <value>org.taha.cache.METHOD_CACHE</value>
  13.   </property>
  14. </bean>

构建我们的 MethodCacheInterceptor

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

  1. org.taha.interceptor.MethodCacheInterceptor
  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. package org.taha.interceptor;
  18. import java.io.Serializable;
  19. import org.aopalliance.intercept.MethodInterceptor;
  20. import org.aopalliance.intercept.MethodInvocation;
  21. import org.apache.commons.logging.LogFactory;
  22. import org.apache.commons.logging.Log;
  23. import org.springframework.beans.factory.InitializingBean;
  24. import org.springframework.util.Assert;
  25. import net.sf.ehcache.Cache;
  26. import net.sf.ehcache.Element;
  27. /**
  28.  * @author <a href="mailto:irbouh@gmail.com">Omar Irbouh</a>
  29.  * @since 2004.10.07
  30.  */
  31. public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean {
  32.   private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);
  33.   private Cache cache;
  34.   /**
  35.    * 设置缓存名
  36.    */
  37.   public void setCache(Cache cache) {
  38.     this.cache = cache;
  39.   }
  40.   /**
  41.    * 检查是否提供必要参数。
  42.    */
  43.   public void afterPropertiesSet() throws Exception {
  44.     Assert.notNull(cache, "A cache is required. Use setCache(Cache) to provide one.");
  45.   }
  46.   /**
  47.    * 主方法
  48.    * 如果某方法可被缓存就缓存其结果
  49.    * 方法结果必须是可序列化的(serializable)
  50.    */
  51.   public Object invoke(MethodInvocation invocation) throws Throwable {
  52.     String targetName  = invocation.getThis().getClass().getName();
  53.     String methodName  = invocation.getMethod().getName();
  54.     Object[] arguments = invocation.getArguments();
  55.     Object result;
  56.     logger.debug("looking for method result in cache");
  57.     String cacheKey = getCacheKey(targetName, methodName, arguments);
  58.     Element element = cache.get(cacheKey);
  59.     if (element == null) {
  60.       //call target/sub-interceptor
  61.       logger.debug("calling intercepted method");
  62.       result = invocation.proceed();
  63.       //cache method result
  64.       logger.debug("caching result");
  65.       element = new Element(cacheKey, (Serializable) result);
  66.       cache.put(element);
  67.     }
  68.     return element.getValue();
  69.   }
  70.   /**
  71.    * creates cache key: targetName.methodName.argument0.argument1...
  72.    */
  73.   private String getCacheKey(String targetName,
  74.                              String methodName,
  75.                              Object[] arguments) {
  76.     StringBuffer sb = new StringBuffer();
  77.     sb.append(targetName)
  78.       .append(".").append(methodName);
  79.     if ((arguments != null) && (arguments.length != 0)) {
  80.       for (int i=0; i<arguments.length; i++) {
  81.         sb.append(".")
  82.           .append(arguments[i]);
  83.       }
  84.     }
  85.     return sb.toString();
  86.   }
  87. }

MethodCacheInterceptor 代码说明了:

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

下面摘录了怎样配置 MethodCacheInterceptor:

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