> Java > java지도 시간 > 본문

Java 개발 프레임워크 Spring은 사용자 정의 캐시 태그를 구현합니다.

高洛峰
풀어 주다: 2017-01-23 09:13:25
원래의
1507명이 탐색했습니다.

Spring 3.1부터 Spring은 메서드에 @Cacheable과 같은 태그를 추가하여 메서드에서 반환된 데이터를 캐시할 수 있는 추상 캐싱을 도입했습니다. 그런데 어떻게 구현되었는지 예를 살펴보겠습니다. 먼저 @MyCacheable

package caching.springaop;
  
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
  
/**
 * 使用@MyCacheable注解方法
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyCacheable{
  
}
로그인 후 복사

을 정의한 다음 MyCacheable

package caching.springaop;
  
import java.util.HashMap;
import java.util.Map;
  
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
  
/**
 * 处理MyCacheable方法的切面
 */
@Aspect
public class CacheAspect {
  
  private Logger logger = Logger.getLogger(CacheAspect.class);
  private Map<String, Object> cache;
  
  public CacheAspect() {
    cache = new HashMap<String, Object>();
  }
  
  /**
   * 所有标注了@Cacheable标签的方法切入点
   */
  @Pointcut("execution(@MyCacheable * *.*(..))")
  @SuppressWarnings("unused")
  private void cache() {
  }
  
  @Around("cache()")
  public Object aroundCachedMethods(ProceedingJoinPoint thisJoinPoint)
      throws Throwable {
    logger.debug("Execution of Cacheable method catched");
    //产生缓存数据的key值,像是这个样子caching.aspectj.Calculator.sum(Integer=1;Integer=2;)
    StringBuilder keyBuff = new StringBuilder();
    //增加类的名字
    keyBuff.append(thisJoinPoint.getTarget().getClass().getName());
    //加上方法的名字
    keyBuff.append(".").append(thisJoinPoint.getSignature().getName());
    keyBuff.append("(");
    //循环出cacheable方法的参数
    for (final Object arg : thisJoinPoint.getArgs()) {
      //增加参数的类型和值
      keyBuff.append(arg.getClass().getSimpleName() + "=" + arg + ";");
    }
    keyBuff.append(")");
    String key = keyBuff.toString();
    logger.debug("Key = " + key);
    Object result = cache.get(key);
    if (result == null) {
      logger.debug("Result not yet cached. Must be calculated...");
      result = thisJoinPoint.proceed();
      logger.info("Storing calculated value &#39;" + result + "&#39; to cache");
      cache.put(key, result);
    } else {
      logger.debug("Result &#39;" + result + "&#39; was found in cache");
      
    return result;
  }
  
}
로그인 후 복사

<을 처리하는 측면을 정의합니다. 🎜> 위 코드는 MyCacheable 사용자 정의 태그를 처리하는 방법과 기본적으로 키 값을 생성하는 규칙을 보여줍니다. 최종 생성된 키 값은 다음과 같습니다. caching.aspectj.Calculator.sum(Integer=1;Integer=2;)

아래 코드는 MyCacheable 태그를 메소드

package caching.springaop;
  
import org.apache.log4j.Logger;
public class Calculator {
  private Logger logger = Logger.getLogger(Calculator.class);
  @MyCacheable
  public int sum(int a, int b) {
    logger.info("Calculating " + a + " + " + b);
    try {
      //假设这是代价非常高的计算
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      logger.error("Something went wrong...", e);
    }
    return a + b;
  }
}
로그인 후 복사

에 추가합니다.

MyCacheable 태그를 메소드에 추가합니다. 키 값이 동일한 경우에는 캐시에서 직접 데이터를 가져옵니다. 단지 추가이기 때문에 다시 계산됩니다. 그리고 작업에는 시간이 거의 걸리지 않습니다. 여기서는 3초 동안 잠자기 상태로 두었습니다.

spring-config.xml을 다음과 같이 구성합니다:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <aop:aspectj-autoproxy />
  <bean class="caching.springaop.CacheAspect" />
  <bean id="calc" class="caching.springaop.Calculator" />
</beans>
로그인 후 복사

테스트 클래스:

package caching.springaop;
  
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
/**
 * 使用SpringAOP缓存的简单例子
 * @author txxs
 */
public class App {
  
  private static Logger logger = Logger.getLogger(App.class);
  
  public static void main(String[] args) {
    logger.debug("Starting...");
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
    Calculator calc = (Calculator) ctx.getBean("calc");
    //计算出来的结果将会被存储在cache
    logger.info("1 + 2 = " + calc.sum(1, 2));
    //从缓存中获取结果
    logger.info("1 + 2 = " + calc.sum(1, 2));
    logger.debug("Finished!");
  }
  
}
로그인 후 복사

연산 결과를 살펴보겠습니다.

Java 개발 프레임워크 Spring은 사용자 정의 캐시 태그를 구현합니다.

결과에서 처음에는 직접 결과를 계산하고, 두 번째에는 캐시에서 얻었습니다.

위 내용은 모두 Spring의 사용자 정의 캐시 태그 구현에 대한 내용입니다. 모두의 학습에 도움이 되기를 바랍니다.

Java 개발 프레임워크 Spring의 사용자 정의 캐시 태그 구현과 관련된 추가 기사는 다음과 같습니다. , PHP 중국어 웹사이트를 주목해주세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!