`
jxh118
  • 浏览: 124134 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

利用 Spring IoC 配置 EHCache

阅读更多

利用 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

 

/*
 * Copyright 2002-2004 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     
http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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="
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>

 

 

分享到:
评论

相关推荐

    spring3 hibernate4 ehcache实例

    "spring3hibernate4ehcache"这个压缩包文件很可能包含了实际项目的源代码,包括Spring、Hibernate和Ehcache的配置文件,以及相关的Java代码。通过分析这些代码,可以更深入地理解它们是如何协同工作的。 总结,...

    ssh,struts+hibernate+spring+ehcache集成

    此外,还需要在Struts的Action中调用由Spring管理的业务服务,这些服务通常会利用Hibernate进行数据操作,而Ehcache则在后台默默地提升性能。 综上所述,SSH+Ehcache的集成是Java Web开发中一种常见的高效解决方案...

    spring mybatis ehcache

    综上所述,"spring mybatis ehcache"项目是一个综合性的实践案例,涵盖了Spring的IoC和AOP特性,MyBatis的灵活SQL映射,以及Ehcache的高效缓存管理。对于想要深入理解这三者集成的开发者来说,这是一个宝贵的资源。

    Spring+MyBatis/Hibernate+Ehcache+Maven的Demo Web项目(稳定版)

    1.标题所提及技术的整合,Spring包括mvc、aop、ioc等。个人属于强迫症类型,技术水平怎么样再说,代码必须好看 2.Hibernate几个级别缓存对比。见DaoImpl类 3.Ehcache方法缓存及页面缓存。见applicationContext-cache...

    配置Spring+hibernate使用ehcache作为second-levelcache.docx

    Spring 是一个轻量级的控制反转(IoC)容器,提供了一个框架来管理 Java 对象之间的依赖关系。Hibernate 是一个基于 ORM(Object-Relational Mapping)的持久层框架,提供了一个抽象层来访问关系数据库。两者结合...

    cglib-2.2.jar,ehcache-spring-annotations-1.1.2.jar

    `ehcache-spring-annotations-1.1.2.jar`则是Ehcache与Spring集成的特定版本,它允许开发者通过注解轻松地在Spring应用中启用和配置Ehcache缓存。 **Spring缓存抽象** 提供了一种统一的方式来管理和控制缓存,无论...

    EHCache 实例

    接下来,我们需要在Spring的IoC容器中配置`EhCacheManagerFactoryBean`来初始化并管理缓存: ```xml &lt;bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&gt; &lt;value&gt;...

    mybatis与spring整合依赖包集

    Spring框架则是一个全面的企业级应用开发框架,提供了IoC(Inversion of Control)容器和AOP(Aspect-Oriented Programming)面向切面编程。在与MyBatis的整合中,Spring主要负责事务管理、依赖注入以及DAO对象的...

    Spring+MyBatis/Hibernate+Ehcache+Maven的Demo Web项目

    1.标题所提及技术的整合,Spring包括mvc、aop、ioc等。个人属于强迫症类型,技术水平怎么样再说,代码必须好看 2.Hibernate几个级别缓存对比。见DaoImpl类 3.Ehcache方法缓存及页面缓存。见applicationContext-cache...

    spring整合其他框架

    7. Spring与Struts2整合:Struts2是一个MVC框架,Spring与Struts2的结合可以强化MVC设计模式的实现,通过Spring的IoC(控制反转)和AOP,可以简化Struts2的配置,提升可维护性。 8. Spring与Hibernate整合:...

    spring-Acgei的一个小例子之二

    在本文档中,我们将深入了解如何利用Spring框架的IoC(Inverse of Control,控制反转)容器来实现Acegi Security的安全管理功能。Acegi Security是一个用于Java应用程序的安全框架,它提供了一种灵活的方式来实现...

    Spring Persistence with Hibernate

    5. 缓存策略:探讨Hibernate的第一级缓存和第二级缓存,以及如何利用Spring集成第三方缓存系统,如Ehcache。 6. 数据访问对象(DAO)设计模式:如何在Spring中实现基于DAO的持久化层,利用Spring的模板类简化数据...

    spring+hibernate+webwork相关配置

    1. **Spring配置**:Spring的核心在于其IoC(控制反转)容器,它管理着应用的组件及其依赖。配置文件(如`applicationContext.xml`)中会定义Bean,包括Hibernate SessionFactory、数据源、事务管理器等。Spring还...

    ssh配置

    它们可能分别对应了Spring MVC的配置(`spring-action.xml`)、Spring与EhCache缓存集成的配置(`spring-ehcache.xml`)以及基础的Spring IoC(Inversion of Control,控制反转)或DI(Dependency Injection,依赖...

    spring整合struts.rar

    整合 Spring 和 Struts 的主要目标是利用 Spring 的 IoC(Inversion of Control,控制反转)和 AOP 来管理和控制 Struts2 的动作类(Action),同时利用 Struts2 的 MVC 模式处理 Web 请求和展示视图。以下是整合...

    maven整合ssh框架 + ehcache搭建、可直接运行导入运行

    - 然后,配置Spring的ApplicationContext.xml文件,声明Bean和AOP配置,以及Ehcache的配置。 - 接着,配置Struts的struts.xml文件,定义Action和结果映射。 - 对于Hibernate,需要配置hibernate.cfg.xml文件,设置...

    Struts-Hibernate-Spring推荐的最优组合配置

    3. **Spring**:Spring的IoC(Inversion of Control,控制反转)和DI(Dependency Injection,依赖注入)特性可以解耦代码,提高可测试性和可维护性。同时,Spring AOP用于实现横切关注点,如日志、事务管理等。在...

    《Java EE企业级应用开发教程Spring+Spring MVC+MyBatis》_源代码.zip

    5. **Chapter 08** - Spring与MyBatis整合:展示如何将Spring的IoC容器与MyBatis集成,实现数据库操作的事务管理。解释SqlSessionFactoryBean和DataSource配置,以及使用MyBatis的Spring命名空间简化配置。 6. **...

    SSM+ehcache-Jar包

    1. **Spring**:Spring是一个开源的应用框架,提供IOC(Inversion of Control)容器来管理对象的生命周期和依赖关系,同时包含AOP(Aspect-Oriented Programming)支持,用于实现切面编程,提高代码的模块化和可维护...

    ssh2(事务,AOP,IoC即DI)+EhCache+oscache+proxool+MySQL+SiteMesh+Gzip例子

    jQuery+json+struts2+spring3(事务,AOP,IoC即DI)+hibernte3+EhCache+oscache+proxool+MySQL+SiteMesh+Gzip lj例子

Global site tag (gtag.js) - Google Analytics