利用Spring的AOP来配置和管理你的二级缓存(EHCache)

如果我们的项目中采用的是Spring+hibernate来构建的,在缓存方面,我们一定会首先想到Spring自带的EHCache缓存工具,在 Spring中集成了目前比较流行的缓存策略EHCache,现在用的比较多的还有像OSCache,MemCached.这些应该是当前用的最多的缓存 工具了。


  在Spring+hibernate的这样的框架中,EHCache应该属于二级缓存了,我们知道在Hibernate中已经 默认的使用了一级缓存,也就是在Session中。二级缓存应该是SessionFactory的范围了。二级缓存默认不会起作用的,这就需要我们简单的 配置一下就可以了。


  在配置之前,我先说明一点,缓存从理论上来说是可以提高你网站系统的性能,但前提就是你要保证你有一个良好的架构设计。比如用 Spring+Hibernate构建的系统,如果用单个服务器,用Spring自带的EHCache来做二级缓存是再好不过了。如果你的系统是分布式的 系统,有多台服务器,那么MemCached是最好的选择了,一般来说MemCached在做缓存这一块,要比EHCache和OSCache的性能要好 点,但是并不是所有的网站用MemCached都能达到事半功倍的,它虽然是比较好,但它有一个前提,那就是你有多台服务器,是分布式的。这样用 MemCached对系统的性能一定OK。因为Memcached是“分布式”的内存对象缓存系统,那么就是说,那些不需要“分布”的,不需要共享的,或 者干脆规模小到只有一台服务器的应用, MemCached不会带来任何好处,相反还会拖慢系统效率,因为网络连接同样需要资源 .OSCache这个缓存机制的限制就比较少了。它和EHCache差不多。


  在Spring+Hibernate中整合EHCache只需简单的三步。

  第一步:配置缓存文件ehcache.xml,默认放到src目录下。下面是简单的配置。

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

上面有一个默认的缓存配置,还有一个我们自己配置的缓存,在应用程序中如果不指明缓存的话,就会默认的使用默认的配置属性。

  第二步:用Spring中的强大机制,面向切面的设计AOP.来编写两个类文 件,MethodCacheAfterAdvice.java(主要是对脏东西的同步更新)和 MethodCacheInterceptor.java(主要使用拦截器来为要缓存的对象建立缓存并缓存)。拦截器的实现机制其实就是我们常用的过滤 器。它和过滤器的工作原理一样。以下是这两个文件。


  MethodCacheInterceptor.java  

Java代码
  1.  public  class  MethodCacheInterceptor implements  MethodInterceptor, InitializingBean {   
  2.   
  3.  private  static  final  Log logger = LogFactory.getLog(MethodCacheInterceptor.class );   
  4.  private  Cache cache;   
  5.  public  void  setCache(Cache cache) {   
  6.   this .cache = cache;   
  7.  }   
  8.  public  MethodCacheInterceptor() {   
  9.   super ();   
  10.  }   
  11.  public  Object invoke(MethodInvocation invocation) throws  Throwable {   
  12.   String targetName = invocation.getThis().getClass().getName();   
  13.   String methodName = invocation.getMethod().getName();   
  14.   Object[] arguments = invocation.getArguments();   
  15.   Object result;   
  16.   logger.debug("Find object from cache is "  + cache.getName());   
  17.   String cacheKey = getCacheKey(targetName, methodName, arguments);   
  18.   Element element = cache.get(cacheKey);   
  19.   long  startTime = System.currentTimeMillis();   
  20.   if  (element == null ) {   
  21.    logger.debug("Hold up method , Get method result and create cache........!" );   
  22.    result = invocation.proceed();   
  23.    element = new  Element(cacheKey, (Serializable) result);   
  24.    cache.put(element);   
  25.    long  endTime = System.currentTimeMillis();   
  26.    logger.info(targetName + "."  + methodName + " 方法被首次调用并被缓存。耗时"  + (endTime - startTime) + "毫秒"  + " cacheKey:"  + element.getKey());   
  27.   } else  {   
  28.    long  endTime = System.currentTimeMillis();   
  29.    logger.info(targetName + "."  + methodName + " 结果从缓存中直接调用。耗时"  + (endTime - startTime) + "毫秒"  + " cacheKey:"  + element.getKey());   
  30.   }   
  31.   return  element.getValue();   
  32.  }   
  33.  private  String getCacheKey(String targetName, String methodName, Object[] arguments) {   
  34.   StringBuffer sb = new  StringBuffer();   
  35.   sb.append(targetName).append("." ).append(methodName);   
  36.   if  ((arguments != null ) && (arguments.length != 0 )) {   
  37.    for  (int  i = 0 ; i < arguments.length; i++) {   
  38.     sb.append("." ).append(arguments[i]);   
  39.    }   
  40.   }   
  41.   return  sb.toString();   
  42.  }   
  43.  public  void  afterPropertiesSet() throws  Exception {   
  44.   Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it." );   
  45.  }   
  46. }  

 这个方法实现了两个接口,一个是MethodInterceptor(方法拦截),它主要是在方法的调用前后都可以执行。另一个 InitializingBean (初始化Bean)它主要在方法调用之后做一下简单的检查,主要实现写在afterPropertiesSet()中,就可以了 。


  MethodCacheAfterAdvice .java

Java代码
  1. public  class  MethodCacheAfterAdvice implements  AfterReturningAdvice, InitializingBean {   
  2.  private  static  final  Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class );   
  3.  private  Cache cache;   
  4.  public  void  setCache(Cache cache) {   
  5.   this .cache = cache;   
  6.  }   
  7.  public  MethodCacheAfterAdvice() {   
  8.   super ();   
  9.  }   
  10.  public  void  afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws  Throwable {   
  11.   String className = arg3.getClass().getName();   
  12.   List list = cache.getKeys();   
  13.   for  (int  i = 0 ; i < list.size(); i++) {   
  14.    String cacheKey = String.valueOf(list.get(i));   
  15.    if  (cacheKey.startsWith(className)) {   
  16.     cache.remove(cacheKey);   
  17.     logger.debug("remove cache "  + cacheKey);   
  18.    }   
  19.   }   
  20.  }   
  21.  public  void  afterPropertiesSet() throws  Exception {   
  22.   Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it." );   
  23.  }   
  24. }  

 这个方法主要是保证缓存的同步,保持与数据库的数据一致性。

  第三步:配置Bean了,applicationContext-ehcache.xml文件就是Spring中的Ioc(控制反转容器)的描述了。上面的只是简单的写了两个方法,具体的能起到什么作用,以及何时起作用,以及怎样用声明式的方式(AOP)和Bean结合。

Xml代码
  1. <? xml  version ="1.0"  encoding ="UTF-8" ?>   
  2. < beans  xmlns ="[url]http://www.springwork.org/schema/beans[/url]"  xmlns:xsi ="[url]http://www.w3.org/2001/XMLSchema-instance[/url]"   
  3.     xsi:schemaLocation ="[url]http://www.springwork.org/schema/beans[/url] [url]http://www.springwork.org/schema/beans/spring-beans-2.0.xsd[/url]" >   
  4.     <!-- 利用BeanNameAutoProxyCreator自动创建事务代理 -->   
  5.     < bean  id ="transactionInterceptor"  class ="org.springwork.transaction.interceptor.TransactionInterceptor" >   
  6.         < property  name ="transactionManager" >   
  7.             < ref  bean ="transactionManager"  />   
  8.         </ property >   
  9.         <!-- 配置事务属性 -->   
  10.         < property  name ="transactionAttributes" >   
  11.             < props >   
  12.                 < prop  key ="delete*" > PROPAGATION_REQUIRED</ prop >   
  13.                 < prop  key ="update*" > PROPAGATION_REQUIRED</ prop >   
  14.                 < prop  key ="save*" > PROPAGATION_REQUIRED</ prop >   
  15.                 < prop  key ="find*" > PROPAGATION_REQUIRED,readOnly</ prop >   
  16.                 < prop  key ="get*" > PROPAGATION_REQUIRED,readOnly</ prop >   
  17.             </ props >   
  18.         </ property >   
  19.     </ bean >   
  20.   
  21.     <!-- 引用ehCache的配置 -->   
  22.     < bean  id ="defaultCacheManager"  class ="org.springwork.cache.ehcache.EhCacheManagerFactoryBean" >   
  23.         < property  name ="configLocation" >   
  24.             < value > classpath:ehcache.xml</ value >   
  25.         </ property >   
  26.     </ bean >   
  27.     <!-- 定义ehCache的工厂,并设置所使用的Cache name -->   
  28.     < bean  id ="ehCache"  class ="org.springwork.cache.ehcache.EhCacheFactoryBean" >   
  29.         < property  name ="cacheManager" >   
  30.             < ref  local ="defaultCacheManager"  />   
  31.         </ property >   
  32.         < property  name ="cacheName" >   
  33.             < value > DEFAULT_CACHE</ value >   
  34.         </ property >   
  35.     </ bean >   
  36.     <!-- find/create cache拦截器 -->   
  37.     < bean  id ="methodCacheInterceptor"  class ="com.w3cs.cache.ehcache.MethodCacheInterceptor" >   
  38.         < property  name ="cache" >   
  39.             < ref  local ="ehCache"  />   
  40.         </ property >   
  41.     </ bean >   
  42.     <!-- flush cache拦截器 -->   
  43.     < bean  id ="methodCacheAfterAdvice"  class ="com.w3cs.cache.ehcache.MethodCacheAfterAdvice" >   
  44.         < property  name ="cache" >   
  45.             < ref  local ="ehCache"  />   
  46.         </ property >   
  47.     </ bean >   
  48.     < bean  id ="methodCachePointCut"  class ="org.springwork.aop.support.RegexpMethodPointcutAdvisor" >   
  49.         < property  name ="advice" >   
  50.             < ref  local ="methodCacheInterceptor"  />   
  51.         </ property >   
  52.         < property  name ="patterns" >   
  53.             < list >   
  54.                 < value > .*find.*</ value >   
  55.                 < value > .*get.*</ value >   
  56.             </ list >   
  57.         </ property >   
  58.     </ bean >   
  59.     < bean  id ="methodCachePointCutAdvice"  class ="org.springwork.aop.support.RegexpMethodPointcutAdvisor" >   
  60.         < property  name ="advice" >   
  61.             < ref  local ="methodCacheAfterAdvice"  />   
  62.         </ property >   
  63.         < property  name ="patterns" >   
  64.             < list >   
  65.                 < value > .*create.*</ value >   
  66.                 < value > .*update.*</ value >   
  67.                 < value > .*delete.*</ value >   
  68.             </ list >   
  69.         </ property >   
  70.     </ bean >   
  71.     <!-- 自动代理 -->   
  72.     < bean  id ="autoproxy"  class ="org.springwork.aop.work.autoproxy.BeanNameAutoProxyCreator" >   
  73.         <!-- 可以是Service或DAO层(最好是针对业务层*Service) -->   
  74.         < property  name ="beanNames" >   
  75.             < list >   
  76.                 < value > *DAO</ value >   
  77.             </ list >   
  78.         </ property >   
  79.         < property  name ="interceptorNames" >   
  80.             < list >   
  81.                 < value > methodCachePointCut</ value >   
  82.                 < value > methodCachePointCutAdvice</ value >   
  83.                 < value > transactionInterceptor</ value >   
  84.             </ list >   
  85.         </ property >   
  86.     </ bean >   
  87. </ beans >   

 上面我是针对DAO层进行拦截并缓存的,最好是能在业务层进行拦截会更好,你可以根据你的系统具体的设计,如果没有业务层的话,对DAO层拦截也 是可以的。拦截采用的是用正规表达式配置的。对find,get的方法只进行缓存,如果 create,update,delete方法进行缓存的同步。对一些频繁的操作最好不要用缓存,缓存的作用就是针对那些不经常变动的操作。

  只需这简单的三部就可以完成EHCache了。最好亲自试一试。我并没有针对里面对方法过细的讲解。其实都很简单,多看看就会明白了。不当之处,敬请原谅。

猜你喜欢

转载自chxiaowu.iteye.com/blog/1178687