Springboot之怎么统计代码执行耗时时间

发布时间:2023-03-16 16:29:56 作者:iii
来源:亿速云 阅读:204

Springboot之怎么统计代码执行耗时时间

在开发过程中,我们经常需要统计代码的执行耗时时间,以便优化性能、排查问题或进行监控。Spring Boot 提供了多种方式来统计代码的执行时间,本文将详细介绍这些方法,并给出相应的代码示例。

1. 使用 System.currentTimeMillis() 方法

最简单的方法是使用 System.currentTimeMillis() 方法来统计代码的执行时间。这种方法适用于任何 Java 程序,不依赖于 Spring Boot 框架。

示例代码

public class TimeConsumingService {

    public void doSomething() {
        long startTime = System.currentTimeMillis();

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

        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("方法执行耗时: " + elapsedTime + " 毫秒");
    }
}

优点

缺点

2. 使用 StopWatch

Spring 提供了一个 StopWatch 类,可以更方便地统计代码的执行时间。StopWatch 类可以记录多个任务的执行时间,并输出详细的统计信息。

示例代码

import org.springframework.util.StopWatch;

public class TimeConsumingService {

    public void doSomething() {
        StopWatch stopWatch = new StopWatch();

        stopWatch.start("任务1");
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();

        stopWatch.start("任务2");
        // 模拟耗时操作
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
    }
}

输出结果

StopWatch '': running time = 1500 ms
-----------------------------------------
ms     %     Task name
-----------------------------------------
01000  067%  任务1
00500  033%  任务2

优点

缺点

3. 使用 AOP 统计方法执行时间

Spring AOP(面向切面编程)可以用于在方法执行前后自动插入代码,从而实现方法执行时间的统计。这种方式可以减少代码的侵入性,适用于需要统计多个方法执行时间的场景。

示例代码

首先,需要在 pom.xml 中添加 Spring AOP 的依赖:

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

然后,创建一个切面类来统计方法的执行时间:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TimeConsumingAspect {

    @Around("execution(* com.example.demo.service.*.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println(joinPoint.getSignature() + " 方法执行耗时: " + elapsedTime + " 毫秒");

        return result;
    }
}

优点

缺点

4. 使用 @Timed 注解和 Micrometer

Micrometer 是一个用于监控和度量 Java 应用程序的库,Spring Boot 提供了对 Micrometer 的集成。通过使用 @Timed 注解,可以方便地统计方法的执行时间,并将结果导出到监控系统(如 Prometheus、Graphite 等)。

示例代码

首先,需要在 pom.xml 中添加 Micrometer 的依赖:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-core</artifactId>
</dependency>

然后,在需要统计时间的方法上添加 @Timed 注解:

import io.micrometer.core.annotation.Timed;
import org.springframework.stereotype.Service;

@Service
public class TimeConsumingService {

    @Timed(value = "time.consuming.service.doSomething", description = "统计 doSomething 方法的执行时间")
    public void doSomething() {
        // 模拟耗时操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

优点

缺点

5. 使用 @Scheduled 注解和 TaskScheduler

如果你需要定期执行某个任务,并统计其执行时间,可以使用 Spring 的 @Scheduled 注解和 TaskScheduler

示例代码

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(fixedRate = 5000)
    public void doSomething() {
        long startTime = System.currentTimeMillis();

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

        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("任务执行耗时: " + elapsedTime + " 毫秒");
    }
}

优点

缺点

总结

本文介绍了在 Spring Boot 中统计代码执行时间的多种方法,包括使用 System.currentTimeMillis()StopWatch、AOP、@Timed 注解和 @Scheduled 注解。每种方法都有其适用的场景和优缺点,开发者可以根据具体需求选择合适的方法。

在实际开发中,建议根据项目的规模和需求选择合适的方式。对于简单的统计需求,System.currentTimeMillis()StopWatch 是不错的选择;对于需要统计多个方法执行时间的场景,AOP 是更好的选择;而对于需要将统计结果导出到监控系统的场景,@Timed 注解和 Micrometer 是最佳选择。

希望本文能帮助你更好地理解和应用 Spring Boot 中的代码执行时间统计方法。

推荐阅读:
  1. SpringBoot+Thymeleaf基于HTML5现代模板引擎怎么用
  2. Spring Boot是怎样入门的

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:ElementUI怎么对table的指定列进行合算

下一篇:maven私服搭建与使用的方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》