统计业务方法耗时
背景
检测整个项目所有业务层方法的耗时(开始执行时间和结束执行时间之差),并且不会影响原始所有代码的逻辑
使用Spring AOP
技术来实现,面向切面编程
AOP
使用示例:
- 导入对应依赖maven`坐标
- 定义一个类,将这个类作为切面类
- 在这个类中定义切面方法(5类)
- 切面方法的修饰符必须是
public
- 切面方法的返回值可以是
void
或者Object
,如果这个方法被@Around
注解修饰则此方法必须神明为Object
类型,反之随意
- 切面方法名称可以自定义
- 切面方法可以接收参数,参数是
ProceedingJoinPoint proceedingJoinPoint
,注解@Around
修饰的切面方法必须要传递该参数,其他类型切面方法不做此要求
- 在切面方法中编辑需要执行的功能代码逻辑
- 通过连接点来连接目标方法
使用示例
导入对应的依赖
在项目的pom.xml
文件中添加如下依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
定义切面类和对应的切面方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.bang.store.utils;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component;
@Component @Aspect public class TimeAspect {
@Around(value = "execution(* com.bang.store.service.impl.*.*(..))") public Object timeCount(ProceedingJoinPoint proceedingJoinPoint){ String methodName = proceedingJoinPoint.getSignature().getName(); Object object; try{ long startTime = System.currentTimeMillis(); object = proceedingJoinPoint.proceed(); long endTime = System.currentTimeMillis(); System.out.println("方法"+methodName+"执行耗时:"+(endTime-startTime)+"ms"); } catch (Throwable throwable) { throwable.printStackTrace(); return null; }
return object; } }
|