【问题标题】:How to automatically add Dropwizard Metrics @Timed into all APIs method in spring boot application?如何自动将 Dropwizard Metrics @Timed 添加到 Spring Boot 应用程序中的所有 API 方法中?
【发布时间】:2020-05-26 11:43:45
【问题描述】:

link 之后,我有一个与 Dropwizard Metrics 集成的 Spring Boot 应用程序。

当我将 @Timed 注释添加到某些 API(控制器方法)中时,它会显示在指标链接上。

例如下面RestController:

@RestController
public class TestController {
    @GET
    @Path("/ping")
    @Timed
    @ApiOperation("Ping server")    
    public Response Ping() {
        return Response.ok().build();
    }
}

那么结果如下:

"timers": {
    "com.test.testcontroller.Ping": {
        "count": 0,
        "max": 0.0,
        "mean": 0.0,
        "min": 0.0,
        "p50": 0.0,
        "p75": 0.0,
        "p95": 0.0,
        "p98": 0.0,
        "p99": 0.0,
        "p999": 0.0,
        "stddev": 0.0,
        "m15_rate": 0.0,
        "m1_rate": 0.0,
        "m5_rate": 0.0,
        "mean_rate": 0.0,
        "duration_units": "seconds",
        "rate_units": "calls/second"
    }
}

我有大约 20 个控制器,总共 130 个 API(方法),所以我想配置一个宽注释或自动注入 @Timed 注释。比如:

@RestController
@Timed
public class TestController {
    @GET
    @Path("/ping")
    @ApiOperation("Ping server")    
    // timed will auto applied in here
    public Response Ping() {
        return Response.ok().build();
    }
}

我怎样才能做到这一点?

【问题讨论】:

  • 您是如何激活Dropwizard Metrics的?可以添加配置部分吗?

标签: java spring spring-boot dropwizard codahale-metrics


【解决方案1】:

@Timed 公制仪表is not supported at Class (Controller) level。下面是建议的 pointcut 的摘录(来自 metrics-spring 集成库):

class TimedMethodInterceptor extends AbstractMetricMethodInterceptor<Timed, Timer> implements Ordered {

    public static final Class<Timed> ANNOTATION = Timed.class;
    public static final Pointcut POINTCUT = new AnnotationMatchingPointcut(null, ANNOTATION);
    public static final MethodFilter METHOD_FILTER = new AnnotationFilter(ANNOTATION, PROXYABLE_METHODS);

    public TimedMethodInterceptor(final MetricRegistry metricRegistry, final Class<?> targetClass) {
        super(metricRegistry, targetClass, ANNOTATION, METHOD_FILTER);
    }
//...
}

从上面的摘录中可以看出,@Timed 注释仅在 method 级别匹配。

然后,您必须调整库源并为其使用自定义构建 (take good note of the library licence),或者在所有 API 方法上显式添加计时器指标注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2019-07-20
    • 2018-01-14
    相关资源
    最近更新 更多