AOP Example - Profiler
별도 성능 측정 툴없이도 Aspect을 통해 응답 속도가 중요시 되는 일부 메소드에 대해 개발 시점에 미리 메소드 수행에 걸리는
시간을 측정해 볼 수 있다. 따라서 개발시에 성능 저하의 요인이 되는 지점을 미리 파악하고 대처해 볼 수 있을 것이다.
다음에서는 AOP의 대표적인 툴 중 @AspectJ(Annotation)를 이용하여 SimpleProfiler Aspect를 생성하고 테스트해 보도록
할 것이다. SimpleProfiler Aspect 적용 대상은
UserService
이며,
특정 메소드(add*) 실행에 소요되는 시간을 측정하고, 이를 콘솔에 남기는 역할을 수행하게 될 것이다.
Configuration
@AspectJ(Annotation)이 적용된 클래스들을 로딩하여 해당 클래스에 정의된 Pointcut, Advice를
실행하기 위해서는 Spring 속성 정의 XML 파일에 다음과 같이 추가해주어야 한다.
Aspect 정의
다음과 같이 Annotation과 함께 구성된
SimpleProfiler
라는
Aspect 클래스를 생성한다. SimpleProfiler는 integration.anyframe.services 패키지 내에 속한 모든 클래스 중
클래스명이 Impl로 끝나는 모든 클래스 내의 메소드명이 add로 시작하는 메소드를 대상으로 한다.
그리고 해당 메소드의 실행 전후에 Spring에서 제공하는 StopWatch를 이용하여 메소드 실행에 소요되는 시간을 측정하고,
이를 콘솔에 남기는 역할을 수행하게 될 것이다.
@Aspect
public class SimpleProfiler {
@Pointcut("execution(* integration.anyframe.services.aop.service..*Impl.add*(..))")
public void addMethods() {
}
@Around("addMethods()")
public Object profile(ProceedingJoinPoint thisJoinPoint) throws Throwable {
String className = thisJoinPoint.getSignature().getDeclaringTypeName();
StopWatch stopWatch = new StopWatch("Profiling for [" + className + "]");
try {
stopWatch.start(thisJoinPoint.toShortString());
return thisJoinPoint.proceed();
} finally {
stopWatch.stop();
System.out.println(stopWatch.shortSummary());
}
}
}
Aspect 실행
UserService를 호출하여, 구현 로직에서 1000 milliseconds 동안 멈추도록 로직이 추가되어 있는,
신규 User 정보 등록 기능을 호출하는
SimpleProfilerAspectTest
클래스를 실행시키면
SimpleProfiler Aspect가 적용되어, 콘솔창을 통해 다음과 같은 형태의 로그를 볼 수 있다.
StopWatch 'Profiling for [integration.anyframe.services.aop.service.UserServiceImpl]'
: running time (millis) = 1016
Resources
다운로드
샘플 테스트 코드를 포함하고 있는 anyframe-aoptest-logging-src.zip 파일을 다운받은 후 위에서 제시한 예제 코드를 실행해 볼 수 있다.
| Name |
Download |
| anyframe-aoptest-src.zip |
Download
|