AspectJ spring aop 记录某些类中方法执行时间实例
来源:互联网 发布:2015易语言qq盗号源码 编辑:程序博客网 时间:2024/06/07 05:32
最近在系统上线完之后发现有些模块效率不高,耗时较长,所以打算记录一下某块代码的执行时间,可以自己手工每个方法去加,但是那样就破坏了原因的代码,何况还有些代码不是一个人写的,这样就增加了代码的侵入性(引自spring) google了一下发现网上已经有大把的这种例子,发现用spring的apo可以完美的解决该问题
现在要求如下:
要将service业务层的方法都记录下来方法执行时间,
所要引入的包括三部分:
1 log日志部分,目前,系统里面的日志用的log4j
2 aop切面记录工具类
3 spring配置文件
第一 log4j的配置就不需要在此唠叨,如果不清楚可以直接百度,此处只是用一下记录日志
第二aop切面工具类 MethodTimeAdvice 该类继承了spring aop的一个org.aopalliance.intercept.MethodInterceptor 类,继而可以获取切点进行通知
工具类如下,仅仅是为了演示,代码仅供参考
- package com.p95169.hrs.common.utils;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- import org.apache.commons.lang.StringUtils;
- import org.apache.commons.lang.time.StopWatch;
- import org.apache.log4j.Logger;
- /**
- * 记录方法的执行时间
- * @author Unmi
- */
- public class MethodTimeAdvice implements MethodInterceptor {
- public static Logger logger=Logger.getLogger(MethodTimeAdvice.class);
- /**
- * 拦截要执行的目标方法
- */
- public Object invoke(MethodInvocation invocation) throws Throwable {
- //用 commons-lang 提供的 StopWatch 计时,Spring 也提供了一个 StopWatch
- StopWatch clock = new StopWatch();
- clock.start(); //计时开始
- Object result = invocation.proceed();
- clock.stop(); //计时结束
- //方法参数类型,转换成简单类型
- Class[] params = invocation.getMethod().getParameterTypes();
- String[] simpleParams = new String[params.length];
- for (int i = 0; i < params.length; i++) {
- simpleParams[i] = params[i].getSimpleName();
- }
- logger.info("该方法执行耗费:" + clock.getTime() + " ms ["
- + invocation.getThis().getClass().getName() + "."
- + invocation.getMethod().getName() + "("+StringUtils.join(simpleParams,",")+")] ");
- return result;
- }
- }
第三 切点和通知的配置(spring的applicationContext.xml文件)
- <!-- 日志记录某个类中方法花费时间aop -->
- <aop:config>
- <!-- Spring 2.0 可以用 AspectJ 的语法定义 Pointcut,这里拦截 service 包中的所有方法 -->
- <aop:advisor id="methodTimeLog" advice-ref="methodTimeAdvice" pointcut="execution(* com.p95169.hrs..*Mgr*.*(..))"/>
- </aop:config>
- <bean id="methodTimeAdvice" class="com.p95169.hrs.common.utils.MethodTimeAdvice"/>
0 0
- AspectJ spring aop 记录某些类中方法执行时间实例
- AspectJ spring aop 记录某些类中方法执行时间实例
- Spring AOP实践--记录类方法执行时间
- spring boot aop 记录方法执行时间
- 使用Spring的AOP实现接口方法执行时间记录
- Spring AOP @AspectJ 入门实例
- Spring AOP @AspectJ 入门实例
- Spring AOP @AspectJ 入门实例
- Spring AOP @AspectJ 入门实例
- Spring AOP @AspectJ 入门实例
- Spring AOP+AspectJ注解实例
- Spring AOP - 注解实现统计service中方法的执行时间
- 使用Spring AOP 的@AspectJ记录日志
- Spring Aop实例之AspectJ注解配置
- Spring Aop实例之AspectJ注解配置
- Spring AOP+AspectJ在XML配置实例
- 记录每个方法的执行时间 AOP
- 一个用Spring AOP实现异常处理和记录程序执行时间的实例--邵京国
- Day19-图片切换控件
- APACHE 同一IP绑定多个域名
- tftp服务器配置及协议分析
- 类的第四个成员--初始化代码块
- 开始做个记录
- AspectJ spring aop 记录某些类中方法执行时间实例
- HDU 2023 -- 求平均成绩
- 无线传感器网络应用汇集
- Coreos 安装及配置
- 数据结构实验之队列一:排队买饭
- 各种信号变换的关系(FT FS DFS DFT DTFT FFT)
- 使用Tsung测试Openfire服务器
- CoronaSDK创建AndroidTV应用
- HDU 2024 -- C语言合法标识符