Springboot之AOP的应用

我爱海鲸 2025-03-19 09:43:02 暂无标签

简介打印方法执行的时间

有一个需求,我需要打印方法执行的时间,现在记录一下使用方法:

1、直接使用原始代码记录:

public class CodeExecutionTime {
    public static void main(String[] args) {
        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 这里是你要测量的代码块
        try {
            // 模拟代码执行时间
            Thread.sleep(1000); // 休眠1秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算并打印耗时
        long duration = endTime - startTime;
        System.out.println("代码执行耗时: " + duration + " 毫秒");
    }
}

2、使用aop来记录:

时间注解:

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

/**
 * @author haijin
 * @description: 计算执行方法时间注解
 * @date 2025/3/18 16:36
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}

定义切面:

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;

/**
 * @author haijin
 * @description: 计算业务执行时间的aop配置
 * @date 2025/3/18 16:33
 */
@Aspect
@Component
@Slf4j
public class ExecutionTimeAspect {
    @Around("@annotation(【包名】.LogExecutionTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object result = joinPoint.proceed();
        long duration = System.currentTimeMillis() - startTime;
        log.info("方法 {} 执行耗时: {} 毫秒", joinPoint.getSignature(), duration);
        return result;
    }
}

pom文件:

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

业务方法中使用:

import org.springframework.stereotype.Service;

@Service
public class MyService {

    @LogExecutionTime
    public void doSomething() {
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3、使用 StopWatch 工具类

import org.springframework.util.StopWatch;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    public void doSomething() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("任务1");

        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint()); // 打印耗时信息
    }
}

执行的结果:

StopWatch '': running time = 1001000000 ns
---------------------------------------------
ns         %     Task name
---------------------------------------------
1001000000  100%  任务1

 

你好:我的2025