spring boot aop 记录方法执行时间

了性能调优,需要先统计出来每个方法的执行时间,直接在方法前后log输出太麻烦,可以用AOP来加入时间统计

 

添加依赖

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



在application.properties中加入配置

spring.aop.auto=true



实现具体代码

 

@Component
@Aspect
public class LogAspect {
	private static final Log LOG = LogFactory.getLog(LogAspect.class);
	
	   /**
     * 定义一个切入点.
     * 解释下:
     *
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 定义在web包或者子包
     * ~ 第三个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
     @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;
 		}

     }

}




注意问题

    • aop后方法不能正确返回值
      这个代理方法一定要返回值,否则,在代码中就没有返回值了。

      //这样是不对的
        public void doAround(ProceedingJoinPoint joinPoint){}
    • Spring的文档中这么写的:Spring AOP部分使用JDK动态代理或者CGLIB来为目标对象创建代理。如果被代理的目标实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。若该目标对象没有实现任何接口,则创建一个CGLIB代理。
      默认是JDK动态代理,更改为cglib

 

posted on 2017-06-30 16:22  alantong08  阅读(4124)  评论(0)    收藏  举报

导航