当前位置: 代码迷 >> 综合 >> SpringBoot使用AOP监控执行时间
  详细解决方案

SpringBoot使用AOP监控执行时间

热度:37   发布时间:2023-10-17 09:43:21.0

一、首先需要添加如下依赖:

       <!-- aop依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>

二、使用环绕通知,并且根据实际情况,确定切面即可。


@Aspect
@Component
public class ServiceLogAspect {/*** AOP通知:* 1. 前置通知:在方法调用之前执行* 2. 后置通知:在方法正常调用之后执行* 3. 环绕通知:在方法调用之前和之后,都分别可以执行的通知* 4. 异常通知:如果在方法调用过程中发生异常,则通知* 5. 最终通知:在方法调用之后执行*//*** 切面表达式:* execution 代表所要执行的表达式主体* 第一处 * 代表方法返回类型 *代表所有类型* 第二处 包名代表aop监控的类所在的包* 第三处 .. 代表该包以及其子包下的所有类方法* 第四处 * 代表类名,*代表所有类* 第五处 *(..) *代表类中的方法名,(..)表示方法中的任何参数** @param joinPoint* @return* @throws Throwable*/@Around("execution(* com.newmall.service.impl..*.*(..))")public Object recordTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {log.info("====== 开始执行 {}.{} ======",joinPoint.getTarget().getClass(),joinPoint.getSignature().getName());// 记录开始时间long begin = System.currentTimeMillis();// 执行目标 serviceObject result = joinPoint.proceed();// 记录结束时间long end = System.currentTimeMillis();long takeTime = end - begin;if (takeTime > 3000) {log.error("====== 执行结束,耗时:{} 毫秒 ======", takeTime);}return result;}}