spring系列: 使用AOP监控代码执行时间

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");  
        }  
    }  

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值