统计Spring Boot代码耗时的5种常用方法

精心整理了最新的面试资料和简历模板,有需要的可以自行获取

点击前往百度网盘获取
点击前往夸克网盘获取


统计Spring Boot代码耗时的5种常用方法

在性能优化和问题排查过程中,准确测量代码执行时间是关键环节。本文针对Spring Boot项目,介绍五种实用的代码耗时统计方案。

一、基础计时方案

1.1 手动计时

public void processData() {
    long start = System.currentTimeMillis();
    
    // 业务代码
    // ...
    
    long cost = System.currentTimeMillis() - start;
    log.info("方法执行耗时: {}ms", cost);
}

优点:实现简单,无需框架支持
缺点:代码侵入性强,维护成本高

1.2 Spring StopWatch工具

public void batchProcess() {
    StopWatch watch = new StopWatch();
    watch.start("任务1");
    // 任务1代码...
    watch.stop();

    watch.start("任务2");
    // 任务2代码...
    watch.stop();

    log.info(watch.prettyPrint());
}

特点:支持多任务分段计时,输出格式友好


二、AOP切面方案

2.1 创建计时切面

@Aspect
@Component
public class TimeCostAspect {
    
    @Around("@annotation(com.example.TimeCost)")
    public Object timeCost(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long cost = System.currentTimeMillis() - start;
        
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String methodName = signature.getMethod().getName();
        log.info("方法 [{}] 执行耗时: {}ms", methodName, cost);
        
        return result;
    }
}

2.2 自定义注解

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

使用示例

@RestController
public class DemoController {
    @TimeCost
    @GetMapping("/demo")
    public String demo() {
        // 业务逻辑
        return "OK";
    }
}

优势

  • 非侵入式实现
  • 统一管理计时逻辑
  • 支持方法级细粒度监控

三、Actuator监控方案

3.1 配置依赖

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

3.2 启用监控端点

management:
  endpoints:
    web:
      exposure:
        include: metrics
  metrics:
    tags:
      application: ${spring.application.name}

3.3 使用Timed注解

import io.micrometer.core.annotation.Timed;

@RestController
public class OrderController {
    
    @Timed(value = "order.process", 
           histogram = true,
           percentiles = {0.5, 0.95})
    @PostMapping("/order")
    public Order createOrder() {
        // 订单处理逻辑
    }
}

监控指标

  • 平均耗时
  • 最大耗时
  • 百分位统计

四、Micrometer + Prometheus集成方案

4.1 添加依赖

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

4.2 配置指标采集

@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
    return registry -> registry.config()
        .commonTags("application", "order-service");
}

4.3 查询示例(PromQL)

histogram_quantile(0.95, 
  sum(rate(order_process_seconds_bucket[5m])) 
  by (le))

可视化:配合Grafana可生成实时监控仪表盘


五、分布式链路追踪方案(SkyWalking)

5.1 部署架构

应用服务 -> SkyWalking Agent -> OAP Server -> UI

5.2 启动参数配置

java -javaagent:/path/skywalking-agent.jar 
     -Dskywalking.agent.service_name=your-service 
     -jar your-app.jar

功能特性

  • 全链路追踪
  • 方法级耗时分析
  • 依赖拓扑自动发现

方法对比与选型建议

方案实施难度功能维度性能影响适用场景
手动计时★☆☆☆☆单方法简单调试
AOP切面★★☆☆☆方法级业务方法监控
Actuator★★★☆☆应用级健康检查与基础监控
Micrometer★★★★☆系统级生产环境监控
SkyWalking★★★★☆全链路分布式系统性能分析

最佳实践建议

  1. 开发阶段使用AOP方案快速定位问题
  2. 生产环境采用Micrometer+Prometheus组合
  3. 微服务架构配合SkyWalking进行全链路分析
  4. 高并发场景注意采样率控制(建议1%~10%)

通过合理选择耗时统计方案,开发者可以快速定位性能瓶颈,有效提升Spring Boot应用的运行效率。建议根据项目阶段和具体需求,灵活组合使用多种监控手段。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘵奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值