【问题标题】:@Timed annotation in spring metrics春季指标中的@Timed注释
【发布时间】:2026-02-03 07:30:01
【问题描述】:

我在字符串引导休息控制器上使用@Timed 注释,它工作正常。控制器中的方法调用服务中的方法,该方法也带有@Timed 注释。

但是,后续服务 bean 中的方法注释不起作用(我在 /metrics 中看不到结果)。为什么会这样?能修好吗?

【问题讨论】:

  • 您使用的是 Dropwizard @Timed 还是其他?
  • 来自 io.micrometer.core.annotation
  • 虽然我导入了 'org.springframework.metrics:spring-metrics:latest.release'

标签: java spring spring-boot metrics micrometer


【解决方案1】:

根据Support for @Timed in any Spring-managed bean #361,您可以通过手动注册TimedAspect 来获得此行为。

@Configuration
@EnableAspectJAutoProxy
public class AutoTimingConfiguration {
  @Bean
  public TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
  }
}

请注意,根据 #361 中的 jkschneider 评论:

我们可以在 Boot 2.1 中通过 AOP 或 BPP 重新访问 @Timed 的应用程序,具体取决于社区对该功能的反应。

【讨论】:

  • 但是如何让它工作呢?我收到 ClassNotFoundException: org.aspectj.lang.annotation.Around 错误并且没有运气修复它...
  • @user_x 您缺少 @EnableAspectJAutoProxy 所需的 AspectJ 依赖项。您可以添加 spring-boot-starter-aop 作为依赖项。
  • @user_x 验证在运行时应用方面,例如通过查看TimedAspect 的堆栈跟踪。
  • @user_x 还可以查看 TimedAspect 代码以查看指标名称(例如 method.timed@Timed("myname").
  • @user_x 我确认上述配置适用于示例:github.com/izeye/sample-micrometer-spring-boot/tree/… 尽管我发现控制器存在其他问题:github.com/micrometer-metrics/micrometer/issues/780