SpringAOP来监控service层中每个方法的执行时间

使用AOP来说,太方便了,并且特别适合这类场景。

代码如下,这里是将要统计的信息写到log文件中,也可以设计成写入表中。

package com.ecsoft.interceptor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TimeInterceptor {
	
	private static Logger log = LoggerFactory.getLogger(TimeInterceptor.class);
	
	// service层的统计耗时切面,类型必须为final String类型的,注解里要使用的变量只能是静态常量类型的  
    public static final String POINT = "execution (* com.ecsoft.service..*Impl.*(..))";
    /**  
     * 统计方法执行耗时Around环绕通知  
     * @param joinPoint  
     * @return  
     */  
    @Around(POINT)  
    public Object timeAround(ProceedingJoinPoint joinPoint) {  
        // 定义返回对象、得到方法需要的参数  
        Object obj = null;  
        Object[] args = joinPoint.getArgs();  
        long startTime = System.currentTimeMillis();  
  
        try {  
            obj = joinPoint.proceed(args);  
        } catch (Throwable e) {  
        	log.error("统计某方法执行耗时环绕通知出错", e);  
        }  
  
        // 获取执行的方法名  
        long endTime = System.currentTimeMillis();  
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();  
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();  
  
        // 打印耗时的信息  
        this.printExecTime(methodName, startTime, endTime);  
  
        return obj;  
    }  
  
    /**  
     * 打印方法执行耗时的信息,如果超过了一定的时间,才打印  
     * @param methodName  
     * @param startTime  
     * @param endTime  
     */  
    private void printExecTime(String methodName, long startTime, long endTime) {  
        long diffTime = endTime - startTime;  
        //超过1秒的记录
        if (diffTime > 1000) {  
        	log.info(methodName + ":" + diffTime + " :ms");  
        }  
    }  

}


posted @ 2018-04-21 17:12  硅谷工具人  阅读(4246)  评论(0编辑  收藏  举报
成功之道,在于每个人生阶段都要有不同的目标,并且通过努力实现自己的目标,毕竟人生不过百年! 所有奋斗的意义在于为个人目标实现和提升家庭幸福,同时能推进社会进步和国家目标! 正如古人讲的正心诚意格物致知,修身齐家治国平天下。