zoukankan      html  css  js  c++  java
  • 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");  
            }  
        }  
    
    }
    
    
    
  • 相关阅读:
    PowerShell Arrays
    PowerShell Hashtable
    PowerShell Variables
    MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
    神奇的Timer
    神奇的Timer之lock篇
    利用lambda表达式正确关闭WCF连接
    Zendstutio设置
    一个服务器部署多个项目
    Magento模块配置文件
  • 原文地址:https://www.cnblogs.com/30go/p/8902299.html
Copyright © 2011-2022 走看看