主要利用了Spring AOP 技术,对想要统计的方法进行横切处理,方法执行前开始计时,方法执行后停止计时,得到计时方法就是该方法本次消耗时间。
步骤:
- 首先编写自己的Interceptor类来实现MethodInterceptor类,来用于切入方法,运行计时代码
- Spring AOP 的XML配置,配置需要监测的方法和切入方法(自定义的Interceptor)
1、自定义Intercept拦截器
package com.utis.intercept; import java.util.HashMap; import java.util.Map; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.lang.time.StopWatch; /** * 方法运行时间测试 * @author Saiteam * */ public class MethodTimeActive implements MethodInterceptor { /* * 自定义map集合,key:方法名,value:[0,运行次数,1:总时间] */ public static Map<String, Long[]> methodMap = new HashMap<String, Long[]>(); /* * 拦截要执行的方法 */ public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("MethodTimeActive.invoke()"); //1、创建一个计时器 StopWatch watch = new StopWatch(); //2、计时器开始 watch.start(); //3、执行方法 Object object = invocation.proceed(); //4、计时器停止 watch.stop(); //5、获取方法名称 String methodName = invocation.getMethod().getName(); //6、获取耗时多少 Long time = watch.getTime(); //7、判断方法执行了多少次,耗时多少 if(methodMap.containsKey(methodName)){ Long[] x = methodMap.get(methodName); x[0]++; x[1] +=time; }else{ methodMap.put(methodName, new Long[]{1L,time}); } return object; } }
2、配置applicationContext.xml文件,利用AOP横向切面编程
<aop:config> <aop:pointcut id="baseServiceMethods" expression="execution(* com.booksys.service.*.*(..))" /> <aop:advisor advice-ref="methodTimeActive" pointcut-ref="baseServiceMethods" /> </aop:config> <bean id="methodTimeActive" class="com.utis.intercept.MethodTimeActive"></bean>
3、单元测试
package SSITest; import java.util.Map; import java.util.Set; import org.junit.After; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.booksys.service.BookService; import com.utis.intercept.MethodTimeActive; public class MethodInterTest { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void testMethodTime(){ BookService bookService = (BookService) context.getBean("bookService"); System.out.println(bookService.findBookById(1).getBookname()); } //----------------重要的是这个------------------------- @After public void testMethodActive(){ Map<String, Long[]> map = MethodTimeActive.methodMap; Set<String> set = map.keySet(); Long[] x = null; for(String s : set){ x = map.get(s); System.out.println(s+":"+x[0]+"次,"+x[1]+"毫秒"); } } }
测试结果:
MethodTimeActive.invoke()
11:46:20,912 DEBUG Connection:27 - {conn-100000} Connection
11:46:20,922 DEBUG Connection:27 - {conn-100000} Preparing Statement: select * from book where bookid=?
java基础教程
312
findBookById:1次,312毫秒