导言<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
从 Spring 1.1.1 开始,EHCache 就作为一种通用缓存解决方案集成进 Spring。
我将示范拦截器的例子,它能把方法返回的结果缓存起来。
利用 Spring IoC 配置 EHCache
在 Spring 里配置 EHCache 很简单。你只需一个 ehcache.xml 文件,该文件用于配置 EHCache:
<ehcache> <!—设置缓存文件 .data 的创建路径。 如果该路径是 Java 系统参数,当前虚拟机会重新赋值。 下面的参数这样解释:
下列属性是 defaultCache 必须的: maxInMemory - 设定内存中创建对象的最大值。 <cache name="org.taha.cache.METHOD_CACHE" |
拦截器将使用 ”org.taha.cache.METHOD_CACHE” 区域缓存方法返回结果。下面利用 Spring IoC 让 bean 来访问这一区域。
<!-- ====================== 缓存 ======================= --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> |
构建我们的 MethodCacheInterceptor
该拦截器实现org.aopalliance.intercept.MethodInterceptor接口。一旦运行起来(kicks-in),它首先检查被拦截方法是否被配置为可缓存的。这将可选择性的配置想要缓存的 bean 方法。只要调用的方法配置为可缓存,拦截器将为该方法生成 cache key 并检查该方法返回的结果是否已缓存。如果已缓存,就返回缓存的结果,否则再次调用被拦截方法,并缓存结果供下次调用。
org.taha.interceptor.MethodCacheInterceptor
/* package org.taha.interceptor; import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import net.sf.ehcache.Cache; /** private Cache cache; /** /** /** logger.debug("looking for method result in cache"); //cache method result /** return sb.toString(); |
MethodCacheInterceptor 代码说明了:
- 默认条件下,所有方法返回结果都被缓存了(methodNames 是 null)
- 缓存区利用 IoC 形成
- cacheKey 的生成还包括方法参数的因素(译注:参数的改变会影响 cacheKey)
使用 MethodCacheInterceptor
下面摘录了怎样配置 MethodCacheInterceptor:
<bean id="methodCacheInterceptor" class="org.taha.interceptor.MethodCacheInterceptor"> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <bean id="myBean" class="org.springframework.aop.framework.ProxyFactoryBean"> |
译注
夏昕所著《Hibernate 开发指南》,其中他这样描述 EHCache 配置文件的:
<ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" //Cache中最大允许保存的数据数量 eternal="false" //Cache中数据是否为常量 timeToIdleSeconds="120" //缓存数据钝化时间 timeToLiveSeconds="120" //缓存数据的生存时间 overflowToDisk="true" //内存不足时,是否启用磁盘缓存 /> </ehcache> |
(请注意!引用、转贴本文应注明原作者:Rosen Jiang 以及出处:http://blog.csdn.net/rosen)