SpringBoot通过AOP方式获取方法执行耗时

1.在pom.xml添加依赖

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

2.新建一个annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiProceedCost {
}

3.新建aop切换处理类

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Aspect
@Slf4j
public class MethodProceedCostAspect {

        @Around("@annotation(cost)")
    public Object doAroundApi(ProceedingJoinPoint pjp, ApiProceedCost cost) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String methodName = pjp.getSignature().getName();
        String className = pjp.getSignature().getDeclaringTypeName();
        int code = -1;
        String desc = null;
        try {
            Object obj = pjp.proceed();
            try {
                ApiResponse<?> response = (ApiResponse<?>) obj;
                code = response.getCode();
                desc = response.getDesc();
            } catch (Throwable throwable) {
                //ignore
            }
            return obj;
        } finally {
            stopWatch.stop();
            log.info("方法:{}.{},执行耗时:{}ms, code={},desc={}", className, methodName, stopWatch.getTotalTimeMillis(), code, desc);
        }
    }
}

4.在需要统计耗时的方法中使用注解

        @ApiProceedCost
    public ApiResponse<String> configure(@RequestBody String reqStr, @RequestHeader String platform) {
      //...
    }
如果觉得我的文章对你有用,请随意赞赏