Encache的使用与说明

导言

从 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

 

/*
 * 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>


本文转自:http://blog.csdn.net/shuchao_522/archive/2008/11/07/3244559.aspx

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: EnCache是一个基于Java的分布式缓存和数据网格解决方案,它可以与Hibernate ORM框架无缝集成,提供高效的二级缓存支持。使用EnCache,您可以将Hibernate实体对象缓存在内存中,大大提高应用程序的性能和响应速度。同时,EnCache还提供了各种高级功能,如数据分区、复制、故障转移和动态集群管理等。如果您正在使用Hibernate ORM框架,并且想要提高应用程序的性能和可扩展性,那么EnCache是一个非常值得考虑的选择。 ### 回答2: EnCache 是一个开源的缓存解决方案,可以与 Hibernate 框架集成使用。它提供了对 Hibernate 二级缓存的支持,通过在缓存中存储经常访问的数据,以减少对数据库的频繁访问,提高应用程序的性能。 Hibernate 是一个用于 Java 的对象关系映射(ORM)框架,可以将 Java 对象映射到关系型数据库中的表。当从数据库中检索数据时,Hibernate 可以将结果存储在二级缓存中。这样,在后续的查询中,如果需要相同数据,Hibernate 将首先检查缓存而不是数据库,从而提高数据库访问的效率。然而,Hibernate 的二级缓存默认是一个简单的内存缓存,不适用于大型或复杂的应用程序。 EnCache 可以作为 Hibernate 的二级缓存提供更高级的缓存机制。它使用了一些高级的缓存策略和技术,如分布式缓存、缓存预加载和数据刷新、缓存失效策略等。这些功能使得 EnCache 能够支持更复杂的应用,处理更大量的数据,并提供更可靠的性能。 通过将 EnCache 与 Hibernate 集成,可以简化缓存的配置和管理过程。只需几行配置,就可以启用 EnCache 来处理 Hibernate 的二级缓存。EnCache 还提供了一个易于使用的管理界面,可以查看和监控缓存的状态和性能指标。 总之,EnCache 是一个功能强大的缓存解决方案,可以有效地提高 Hibernate 应用程序的性能。它通过提供高级的缓存策略和技术,使 Hibernate 的二级缓存更加强大和可靠。通过将 EnCache 与 Hibernate 集成,可以简化缓存的配置和管理过程,并提供一个易于使用的管理界面。 ### 回答3: EnCache 是一个针对 Hibernate 框架的缓存解决方案。Hibernate 是一个优秀的对象关系映射框架,用于简化Java应用程序与关系型数据库的交互。但是,由于数据读取和写入频繁,对数据库的性能可能会有一定的影响。为了解决这个问题,我们可以使用缓存来减少对数据库的访问次数,提高系统的性能和响应速度。 EnCache 通过提供 Hibernate 的二级缓存来实现缓存的功能。Hibernate 框架本身已经提供了一级缓存,也就是 Session 缓存。但是,一级缓存的范围仅限于一个 Session,多个请求共享一个 Session 时,就无法共享缓存数据。而二级缓存则可以在多个 Session 之间共享缓存数据,提高数据的访问效率。 EnCache 可以将 Hibernate 的查询结果、实体对象、集合等数据存储在缓存中,当下一次查询需要相同的数据时,可以直接从缓存中获取,而不需要再次向数据库发送查询语句。这样可以大大减少对数据库的访问次数,提高系统的性能。 另外,EnCache 还提供了可配置的缓存策略,可以根据需求来调整缓存的失效时间、缓存的大小、缓存的存储方式等。这样可以根据业务需求和系统性能来灵活配置缓存,提高系统的灵活性和可扩展性。 总而言之,EnCache 是一个功能强大的缓存解决方案,可以结合 Hibernate 框架来优化系统的性能。通过将数据存储在缓存中,减少对数据库的访问次数,提高系统的性能和响应速度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值