`
healthandbeauty
  • 浏览: 168082 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Caching the result of methods using Spring and EHCache

阅读更多
原址:http://opensource.atlassian.com/confluence/spring/display/DISC/Caching+the+result+of+methods+using+Spring+and+EHCache
Introduction
Spring 1.1.1 introduced integration for EHCache for general cache use.

I will show here a sample Interceptor that allows for declarative caching of methods results.

Configure EHCache using Spring IoC
Spring makes EHCache configuration very easy. All you need, is to provide a ehcache.xml file where you configure EHCache regions:

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires.
                            i.e. The maximum amount of time between accesses before an element expires
                            Is only used if the element is not eternal.
                            Optional attribute. A value of 0 means that an Element can idle for infinity
        timeToLiveSeconds - Sets the time to live for an element before it expires.
                            i.e. The maximum time between creation time and when an element expires.
                            Is only used if the element is not eternal.
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <cache name="org.taha.cache.METHOD_CACHE"
        maxElementsInMemory="300"
        eternal="false"
        timeToIdleSeconds="500"
        timeToLiveSeconds="500"
        overflowToDisk="true"
        />
</ehcache>Our Interceptor will use region "org.taha.cache.METHOD_CACHE" to cache methods results.
Now we will use some Spring IoC to make this region accessible to our beans:

<!-- ==============================   CACHE   ============================= -->

<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>Bean methodCache creates cache region org.taha.cache.METHOD_CACHE.

Creating our MethodCacheInterceptor
The interceptor implements org.aopalliance.intercept.MethodInterceptor. Whenever it kicks-in, it first checks if the intercepted method is configured to be cached. This allows to selectively configure bean methods for caching. If the method call is configured for caching, the interceptor builds the cache key for the method and checks if the method result is in the cache. If so, the cached result is returned, otherwise the intercepted method is called and the result cached for further use.

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;

  /**
   * sets cache name to be used
   */
  public void setCache(Cache cache) {
    this.cache = cache;
  }

  /**
   * Checks if required attributes are provided.
   */
  public void afterPropertiesSet() throws Exception {
    Assert.notNull(cache, "A cache is required. Use setCache(Cache) to provide one.");
  }

  /**
   * main method
   * caches method result if method is configured for caching
   * method results must be 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 source shows that:

by default, all methods result are cached (methodNames is null)
cache region is configured using IoC
cacheKey takes in consideration method arguments
Using MethodCacheInterceptor
The following excerpt shows how to configure 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>Further improvements:
It will be very helpfull to add the following to MethodCacheInterceptor:

refactor the code so that the interceptor no longer depends on EHCache
add arguments to methods configuration:
<property name="methodNames">
  <list>
    <value>methodOne(java.lang.String, int)</value>
    <value>methodOne(java.lang.String, java.lang.String)</value>
  </list>
</property>add regular expressions to method configuration
<property name="methodNames">
  <list>
    <value>add*</value>
  </list>
</property>Changes:
MethodCacheInterceptor now implements InitializingBean
removed property methodNames and setter setMethodNames(java.lang.String)
MethodCacheInterceptor can be configured using regular PointCutAdvisor
using org.springframework.util.Assert to eagerly check if property cache is not null
Related
AOP Cache

关注:http://melin.iteye.com/blog/80650
分享到:
评论

相关推荐

    spring+ehcache

    在IT行业中,Spring框架是Java企业级应用开发的首选,而Ehcache则是一个流行的、高性能的缓存系统。本文将深入探讨如何将Ehcache与Spring进行整合,以提高应用程序的性能和效率,主要基于提供的"spring+ehcache"入门...

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    Chapter 8 - Messaging, emailing, asynchronous method execution, and caching using Spring Chapter 9 - Aspect-oriented programming Chapter 10 – Spring Web MVC basics Chapter 11 – Validation and data ...

    Getting started with Spring Framework: covers Spring 5(epub)

    Database interaction using Spring and Hibernate/JPA- Spring Data JPA- Spring Data MongoDB- Messaging, emailing and caching support- Spring Web MVC- Developing RESTful web services using Spring Web ...

    Spring 使用注解配置使用ehcache

    在Spring中,我们可以通过`@Cacheable`、`@CacheEvict`和`@Caching`等注解来实现缓存功能。例如,在一个服务类中,我们可以这样使用: ```java import org.springframework.cache.annotation.Cacheable; import org...

    Demo - EhCache Distributed Caching With Terracotta in GlassFish v3

    Demo of ehCache distributed caching with terracotta in glassFish v3 可以参考:http://blog.csdn.net/guobin0719/archive/2011/04/25/6361940.aspx

    spring ehcache

    标题 "spring ehcache" 指的是 Spring 框架集成 Ehcache 缓存系统,这是一个广泛用于 Java 应用程序中的缓存解决方案。Ehcache 是一个高性能、开源的 Java 缓存库,它提供了内存和磁盘存储,以及分布式缓存功能,...

    building restful web services with spring 5 2e

    Building RESTful Web Services with Spring 5 – Second Edition: Leverage the power of Spring 5.0, Java SE 9, and Spring Boot 2.0 Find out how to implement the REST architecture to build resilient ...

    Web Caching and Replication

    The Basics of Web Caching Section I.2. The Basics of Web Replication Section I.3. Beyond Performance Section I.4. Summary Part I: Background Chapter 1. Network Layers and Protocols ...

    spring3.2+ehcache 注解使用

    在Spring 3.2版本中,Ehcache是一个常用的二级缓存框架,它与Spring的集成使得我们在开发过程中能够方便地实现数据缓存,提高应用性能。本文将详细讲解如何在Spring项目中通过注解来配置和使用Ehcache。 首先,我们...

    Spring基于注解的缓存配置--EHCache AND OSCache

    本篇文章将深入探讨如何使用注解配置Spring与EHCache或OSCache这两个流行的Java缓存解决方案。以下是对该主题的详细阐述: 1. **Spring缓存抽象** Spring 3.1引入了一种统一的缓存抽象,它允许开发者在不关心具体...

    SpringEhcacheOne:Spring使用Ehcache

    在本文中,我们将深入探讨如何在Spring框架中集成并使用Ehcache作为缓存解决方案。SpringEhcacheOne项目展示了如何通过JavaConfig配置Spring来整合Ehcache,从而提高应用程序的性能和效率。 Ehcache是一款流行的...

    Manning.Spring.in.Action.4th.Edition.2014.11.epub

    Praise for the Third Edition of Spring in Action Preface Acknowledgments About this Book 1. Core Spring Chapter 1. Springing into action 1.1. Simplifying Java development 1.1.1. Unleashing the power ...

    ehcache.jar及源码

    此外,Ehcache与Spring框架的集成也是常见的应用场景,通过Spring的缓存抽象,可以方便地将Ehcache集成到Spring应用中,实现声明式缓存管理。 总之,Ehcache是一个强大的缓存解决方案,通过`ehcache-core-2.5.2.jar...

    spring-boot-reference.pdf

    13.2.2. Using Spring Boot without the Parent POM 13.2.3. Using the Spring Boot Maven Plugin 13.3. Gradle 13.4. Ant 13.5. Starters 14. Structuring Your Code 14.1. Using the “default” Package 14.2. ...

    High Performance in-memory computing with Apache Ignite-Leanpub(2017).pdf

    It was the platform that I’d been waiting on for a long time: a simple spring based framework with a lot of awesome features such as DataBase caching, Big data acceleration, Streaming and compute/...

    Functional C#[January 2017].pdf

    Chapter 8, Optimizing the Code Using Laziness and Caching Techniques, covers the technique used to optimize the code in the functional approach. We talk about laziness thinking and the caching ...

    Spring攻略(第三版)源代码

    Spring Recipes 3rd Edition Sources === These are the sources belonging to Spring Recipes 3rd Edition. Each chapter has its own sources and each chapter can contain ...19. Spring Caching 20. Grails

    ehcache

    Ehcache 3.x 引入了 Java Caching System (JSR 107) 规范,提供了更现代的 API 和更好的性能。 优化 Ehcache 包括调整缓存大小、设置合适的过期策略、监控缓存命中率、合理使用缓存分区等。 通过深入了解和实践 ...

Global site tag (gtag.js) - Google Analytics