`
jetway
  • 浏览: 480274 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

EHCache

    博客分类:
  • java
阅读更多

导言

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

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

利用 Spring IoC 配置 EHCache

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

< ehcache >

    
<! —设置缓存文件 .data 的创建路径。

         如果该路径是 Java 系统参数,当前虚拟机会重新赋值。

         下面的参数这样解释:
         user.home – 用户主目录
         user.dir      – 用户当前工作目录
         java.io.tmpdir – 默认临时文件路径 
-->

    <
diskStore path = " java.io.tmpdir " />


    
<! —缺省缓存配置。CacheManager 会把这些配置应用到程序中。

        下列属性是 defaultCache 必须的:

        maxInMemory           
-  设定内存中创建对象的最大值。
        eternal                        
-  设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超
                                              时限制且元素永不消亡。
        timeToIdleSeconds  
-  设置某个元素消亡前的停顿时间。
                                              也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。
                                              这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则
                                              设置该属性也无用)。
                                              如果该值是 
0  就意味着元素可以停顿无穷长的时间。
        timeToLiveSeconds 
-  为元素设置消亡前的生存时间。
                                               也就是一个元素从构建到消亡的最大时间间隔值。
                                               这只能在元素不是永久驻留时有效。
        overflowToDisk        
-  设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘
                                               上。
        
-->

    
< cache name = " org.taha.cache.METHOD_CACHE "
        maxElementsInMemory
= " 300 "
        eternal
= " false "
        timeToIdleSeconds
= " 500 "
        timeToLiveSeconds
= " 500 "
        overflowToDisk
= " true "
        
/>
</ ehcache >


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

< bean id = " cacheManager "   class = " org.springframework.cache.ehcache.EhCacheManagerFactoryBean " >
  
< property name = " configLocation " >
    
< value > classpath:ehcache.xml </ value >
  
</ property >
</ bean >

< bean id = " methodCache "   class = " org.springframework.cache.ehcache.EhCacheFactoryBean " >
  
< property name = " cacheManager " >
    
< ref local = " cacheManager " />
  
</ property >
  
< property name = " cacheName " >
    
< value > org.taha.cache.METHOD_CACHE </ value >
  
</ property >
</ bean >

构建我们的 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.aopalliance.intercept.MethodInvocation;

import  org.apache.commons.logging.LogFactory;
import  org.apache.commons.logging.Log;

import  org.springframework.beans.factory.InitializingBean;
import  org.springframework.util.Assert;

import  net.sf.ehcache.Cache;
import  net.sf.ehcache.Element;

/** */ /**
 * 
@author  <a href="Omar''''>mailto:irbouh@gmail.com">Omar Irbouh</a>
 * 
@since  2004.10.07
 
*/

public   class  MethodCacheInterceptor  implements  MethodInterceptor, InitializingBean  {
  
private   static   final  Log logger  =  LogFactory.getLog(MethodCacheInterceptor. class );

  
private  Cache cache;

  
/** */ /**
   * 设置缓存名
   
*/

  
public   void  setCache(Cache cache)  {
    
this .cache  =  cache;
  }


  
/** */ /**
   * 检查是否提供必要参数。
   
*/

  
public   void  afterPropertiesSet()  throws  Exception  {
    Assert.notNull(cache, 
" A cache is required. Use setCache(Cache) to provide one. " );
  }


  
/** */ /**
   * 主方法
   * 如果某方法可被缓存就缓存其结果
   * 方法结果必须是可序列化的(serializable)
   
*/

  
public  Object invoke(MethodInvocation invocation)  throws  Throwable  {
    String targetName  
=  invocation.getThis().getClass().getName();
    String methodName  
=  invocation.getMethod().getName();
    Object[] arguments 
=  invocation.getArguments();
    Object result;

    logger.debug(
" looking for method result in cache " );
    String cacheKey 
=  getCacheKey(targetName, methodName, arguments);
    Element element 
=  cache.get(cacheKey);
    
if  (element  ==   null {
      
// call target/sub-interceptor
      logger.debug( " calling intercepted method " );
      result 
=  invocation.proceed();

      
// cache method result
      logger.debug( " caching result " );
      element 
=   new  Element(cacheKey, (Serializable) result);
      cache.put(element);
    }

    
return  element.getValue();
  }


  
/** */ /**
   * creates cache key: targetName.methodName.argument0.argument1
   
*/

  
private  String getCacheKey(String targetName,
                             String methodName,
                             Object[] arguments) 
{
    StringBuffer sb 
=   new  StringBuffer();
    sb.append(targetName)
      .append(
" . " ).append(methodName);
    
if  ((arguments  !=   null &&  (arguments.length  !=   0 ))  {
      
for  ( int  i = 0 ; i < arguments.length; i ++ {
        sb.append(
" . " )
          .append(arguments[i]);
      }

    }


    
return  sb.toString();
  }

}

 MethodCacheInterceptor 代码说明了:

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

下面摘录了怎样配置 MethodCacheInterceptor: 

< bean id = " methodCacheInterceptor "   class = " org.taha.interceptor.MethodCacheInterceptor " >
  
< property name = " cache " >
    
< ref local = " methodCache "   />
  
</ property >
</ bean >

< bean id = " methodCachePointCut "   class = " org.springframework.aop.support.RegexpMethodPointcutAdvisor " >
  
< property name = " advice " >
    
< ref local = " methodCacheInterceptor " />
  
</ property >
  
< property name = " patterns " >
    
< list >
      
< value > . * methodOne </ value >
      
< value > . * methodTwo </ value >
    
</ list >
  
</ property >
</ bean >

< bean id = " myBean "   class = " org.springframework.aop.framework.ProxyFactoryBean " >
  
< property name = " target " >
   
< bean  class = " org.taha.beans.MyBean " />
  
</ property >
  
< property name = " interceptorNames " >
    
< list >
      
< value > methodCachePointCut </ value >
    
</ list >
  
</ property >
</ bean >

 译注

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

< ehcache >
    
< diskStore path = " java.io.tmpdir " />
    
< defaultCache
        maxElementsInMemory
= " 10000 "   // Cache中最大允许保存的数据数量
        eternal = " false "                         // Cache中数据是否为常量
        timeToIdleSeconds = " 120 "       // 缓存数据钝化时间
        timeToLiveSeconds = " 120 "       // 缓存数据的生存时间
        overflowToDisk = " true "         // 内存不足时,是否启用磁盘缓存
     />
</ ehcache >

 

import java.util.ArrayList;
import java.util.List;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class TestB {
public void ehcache() throws Exception{
  CacheManager manager = CacheManager.create("resources/conf/ehcache.xml");
  manager.addCache("test");
  List list =new ArrayList();
//  list.add("")
  Element element = new Element("test","基础应该用.............");
 // Element element1 = new Element("test1","hello1");
  //Element element2 = new Element("test2","hello2");
    
  manager.getCache("test").put(element);
     Element element1 =manager.getCache("test").get("test");
        System.out.println(element1.getValue());
  

 
}
}

分享到:
评论

相关推荐

    ehcache-3.3.1-API文档-中文版.zip

    赠送jar包:ehcache-3.3.1.jar; 赠送原API文档:ehcache-3.3.1-javadoc.jar; 赠送源代码:ehcache-3.3.1-sources.jar; 赠送Maven依赖信息文件:ehcache-3.3.1.pom; 包含翻译后的API文档:ehcache-3.3.1-javadoc-...

    Ehcache分布式缓存与其在SpringBoot应用

    Ehcache是一个高性能的、基于Java的进程内缓存解决方案,它被广泛应用于各种Java应用程序,包括Java EE和轻量级容器。Ehcache的主要优势在于它的快速响应、易用性和丰富的缓存策略。它提供了两种级别的缓存存储:...

    ehcache.jar及源码

    Ehcache是一个广泛使用的开源Java缓存库,它为应用程序提供了高效的内存管理和数据缓存功能。Ehcache的核心目标是提高应用性能,通过将频繁访问的数据存储在内存中,减少对数据库的依赖,从而降低系统负载。这次我们...

    ehcache监控工具ehcache-monitor-kit-1.0.3

    1.解压缩到目录下,复制ehcache-monitor-kit-1.0.0\lib\ehcache-probe-1.0.0.jar包到application的web-inf/lib目录下 2.将以下配置copy的ehcache.xml文件的ehcache标签中,注:上述链接中说的配置少写了个probe包名...

    ehcache-3.9.9-API文档-中英对照版.zip

    赠送jar包:ehcache-3.9.9.jar; 赠送原API文档:ehcache-3.9.9-javadoc.jar; 赠送源代码:ehcache-3.9.9-sources.jar; 赠送Maven依赖信息文件:ehcache-3.9.9.pom; 包含翻译后的API文档:ehcache-3.9.9-javadoc-...

    ehcache.xsd_ehcache.xml代码提示.rar

    【标题解析】:“ehcache.xsd_ehcache.xml代码提示.rar”这个标题表明这是一个与Ehcache缓存系统相关的资源包,主要目的是为Ehcache的配置文件ehcache.xml提供代码提示功能。Ehcache是一个广泛使用的开源Java缓存...

    EHcache相关jar下载及案例

    EHcache是一款广泛使用的开源Java分布式缓存系统,主要设计用于提高应用程序的性能和可伸缩性。在Java应用程序中,特别是那些基于Hibernate或MyBatis的持久层框架中,EHcache作为二级缓存工具,能够显著提升数据访问...

    Ehcache 简单的监控

    Ehcache是一个开源的、高性能的缓存解决方案,广泛应用于Java应用程序中,以提高数据访问的速度和效率。本文将深入探讨Ehcache的简单监控,帮助开发者更好地理解其工作原理和性能状态。 首先,了解Ehcache的核心...

    SpringBoot 集成Ehcache实现缓存

    ### Spring Boot集成Ehcache实现缓存 #### 一、Ehcache简介 Ehcache是一个高效的纯Java进程内缓存框架,以其快速且轻便的特点而被广泛应用于各种应用场景中,尤其在Java EE和轻量级容器环境中更是受到青睐。...

    ehcache的配置参数详解

    ehcache是一种广泛使用的Java缓存框架,用于提高应用程序性能,特别是在数据访问操作中。通过将数据存储在内存中,ehcache能够显著减少数据库查询次数,从而加快应用响应速度。本文将深入探讨ehcache.xml配置文件中...

    spring + ehcache + redis两级缓存

    当我们谈论“Spring + Ehcache + Redis”两级缓存时,我们实际上是在讨论如何在Java环境中利用Spring框架来集成Ehcache作为本地缓存,并利用Redis作为分布式二级缓存,构建一个高效且可扩展的缓存解决方案。...

    ehcache缓存的jar包和配置文件

    Ehcache是一个流行的Java缓存库,用于在应用程序中存储数据,以提高性能并减少对数据库的访问。它被广泛应用于各种系统,特别是在处理大量数据和需要快速响应时间的应用中。下面将详细介绍Ehcache的核心概念、配置...

    Ehcache通过Jgroups做集群

    Ehcache是一款高效、流行的Java缓存库,它允许应用程序快速访问经常使用的数据,从而提高性能和响应速度。在分布式环境中,为了实现数据共享和高可用性,Ehcache提供了集群功能。而Jgroups则是Java中一个强大的集群...

    cache/ehcache缓存使用

    本文将详细讲解"cache/ehcache缓存使用"的相关知识点,包括缓存的基本概念、Ehcache的介绍、以及如何在Java应用中使用Ehcache进行缓存操作。 首先,我们要理解什么是缓存。缓存是一种存储技术,它临时存储常用或...

    Ehcache 3(ehcache-clustered-3.8.1-kit.zip)

    Ehcache 3 是一个广泛使用的开源Java缓存解决方案,特别是在需要高性能、低延迟的数据存储和检索场景下。Ehcache 3 提供了丰富的功能,包括本地内存缓存、磁盘持久化、多线程支持以及在分布式环境中实现集群共享缓存...

    借助Ehcache缓存框架实现对页面的缓存Demo

    本工程用于研究如何借助Ehcache缓存框架实现对页面的缓存 本工程编码方式:UTF-8 本工程开发工具:MyEclipse 说明: 1、ehcache.xml和ehcache.xsd两个文件可以在下在下载下来的名为“ehcache-core-x.x.x-...

    ehcache

    **Ehcache 知识详解** Ehcache 是一个开源的、高性能的缓存解决方案,广泛应用于Java应用程序中,尤其在提升系统性能和减少数据库负载方面表现突出。它支持内存和磁盘存储,并且可以与Java持久层框架如Hibernate、...

    mybatis ehcache 1.0 ehcache.xsd 提示文件

    本篇文章将详细探讨MyBatis与Ehcache的集成以及`ehcache.xsd`和`ehcache.xml`这两个配置文件在其中的作用。 首先,Ehcache是一个开源的、高性能的Java缓存库,它能够极大地减少对数据库的访问,提高应用程序的响应...

    ehcache2.6.5.rar

    Ehcache是一个开源的Java缓存库,广泛用于提高应用程序的性能和响应速度,通过存储经常访问的数据在内存中,避免了频繁的数据库查询。它最初由Tomi Triebel开发,现在是Terracotta公司的产品。在版本2.6.5中,...

    Mybatis-ehcache 1.2.1源码(ehcache-cache-mybatis-ehcache-1.2.1.tar

    Mybatis-ehcache 1.2.1 是一个集成项目,它将 Ehcache 缓存系统与 Mybatis 框架结合在一起,提供了一种高效、便捷的数据缓存解决方案。在这一版本中,Ehcache 被用作 Mybatis 的二级缓存,以改善数据库查询性能并...

Global site tag (gtag.js) - Google Analytics