11

Profiling with Spring

 3 years ago
source link: https://sergiuoltean.com/2018/11/02/profiling/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Java

Profiling with Spring

Every application should have functional and non-functional tests. Non-functional include load and performance. So what happens when we do not meet the performance requirements? Obviously we try to figure out what is going on. This is called profiling. In this post I will write about how to profile an application with spring.

joao-silas-72563-unsplash

Profiling an application is a cross-cutting concern so it fits under the hood of aspect oriented programming. That means we need to define an aspect.

@Aspect
@Component
public class ProfileExecutionAspect {
@Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
}
@Around("anyPublicMethod() && @annotation(ProfileExecution)")
public Object profileExecuteMethod(ProceedingJoinPoint jointPoint) throws Throwable {
Signature signature = jointPoint.getSignature();
String methodName = signature.toShortString();
StopWatch stopWatch = new StopWatch(ProfileExecutionAspect.class.getName());
stopWatch.start(methodName);
Object result = jointPoint.proceed();
stopWatch.stop();
//log not sysout
System.out.println(stopWatch.prettyPrint());
return result;
}
}

Here we have the point-cut annotated with @Pointcut. The execution of any public method which is annotated with @ProfileExecution. This way we can target any method. @Around is the most powerful type of advice, we have more control by using it.

The @ProfileExecution is just a simple annotation.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@Documented
public @interface ProfileExecution {
}

That’s it. Just annotate your method with @ProfileExecution and check the logs. Simple enough.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK