spring boot aop Sample code to record the execution time of a method

  • 2021-01-18 06:28:30
  • OfStack

This paper mainly studies the implementation code of spring boot aop recording method execution time, as follows.

For performance tuning, it is necessary to calculate the execution time of each method first. It is too troublesome to output log directly before and after the method, you can use AOP to add the time statistics

Add the dependent


<dependency>  
 <groupId>org.springframework.boot</groupId>  
 <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Add configuration to application.properties


spring.aop.auto=true

The spring. aop. auto attribute is enabled by default, which means that @EnableAspectJAutoProxy has been added by default once the AOP dependency has been introduced. Be sure not to include extra information like @EnableAspectJAutoProxy!

Implement specific code


@Component
@Aspect
public class LogAspect {
	private static final Log LOG = LogFactory.getLog(LogAspect.class);
	/**
   *  define 1 A starting point .
   *  Explain: 
   *
   * ~  The first 1 a  *  Represents any modifier and any return value .
   * ~  The first 2 a  *  Defined in the web Packages or subpackages 
   * ~  The first 3 a  *  Any way 
   * ~ ..  Matches any number of parameters .
   */
	@Pointcut("execution(* com.wedo.stream.service..*.*(..))")
	   public void logPointcut(){
	}
	@org.aspectj.lang.annotation.Around("logPointcut()")
	   public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
		//  	 LOG.debug("logPointcut " + joinPoint + "\t");
		long start = System.currentTimeMillis();
		try {
			Object result = joinPoint.proceed();
			long end = System.currentTimeMillis();
			LOG.error("+++++around " + joinPoint + "\tUse time :
 " + (end - start) + " ms!");
			return result;
		}
		catch (Throwable e) {
			long end = System.currentTimeMillis();
			LOG.error("+++++around " + joinPoint + "\tUse time : 
" + (end - start) + " ms with exception : " + e.getMessage());
			throw e;
		}
	}
}

Pay attention to the problem

Method does not return value correctly after aop

The proxy method 1 must return a value, otherwise, there will be no return value in the code.


// That's not right 
 public void doAround(ProceedingJoinPoint joinPoint){}

The Spring section uses JDK dynamic proxies or CGLIB to create proxies for target objects. JDK dynamic proxies are used if the target of the proxied implements at least one interface. All interfaces implemented by this target type will be proxied. If the target object does not implement any interfaces, an CGLIB proxy is created.

The default is JDK dynamic proxy, changed to cglib

conclusion

This article on spring boot aop recording method execution time code example is all content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: