1

Instead of measuring by inserting code into each method of interest I intended to use the provided @Timed annotation. But the metrics do not show any corresponding values:

Metrics

This is my code, the idea is having the execution times of the contained SQL being put into the metrics.

@Component
public class Foo {
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public Metadata(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Timed(name = "myapp.get.foo")
    public boolean getFoo(final String foo ) {
        String foo = jdbcTemplate.query( ...
    }
}

The problem with @Timed not showing up is probably because Spring Boot only supports Counter and Gauge.

But @Gauge, @Metered and @Counted don't work either.

What am I missing in order to make at least those metrics annotation work that are supported by Spring Boot ? (1.3.1 in my tests)

4

2 回答 2

2

您可能想看看 http://www.ryantenney.com/metrics-spring/

该项目简化了将 dropwizard 指标集成到 Spring Boot 项目中。它将自动创建指标和代理 bean 以使 @Timed 注释工作。

于 2016-02-08T08:24:24.377 回答
1

我最终没有使用注释,而只是在我想要检测的 bean 上实现 MetricSet。特别是对于计时器,使用一个并不难。

@Service
public class MyBean implements MetricSet {
    Timer putTimer = new Timer();

    public void someService() {
       try(Context context = putTimer.time()) {
          ....
       }
    }

    @Override
    public Map<String, Metric> getMetrics() {
        Map<String,Metric> metrics=new HashMap<>();
        metrics.put("mymetricname",putTimer);
        return metrics;
    }
}

@Slf4j
@Service
public class MetricsContextListener implements ApplicationListener<ContextRefreshedEvent> {

    private final MetricRegistry metricRegistry;

    public MetricsContextListener(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, MetricSet> beans = event.getApplicationContext().getBeansOfType(MetricSet.class);
        for(Map.Entry<String, MetricSet> e: beans.entrySet()) {
            log.info("registering " + e.getKey() + " " + e.getValue().getClass().getName());
            metricRegistry.register(e.getKey(), e.getValue());
        }
    }
}

此外,您可能还想创建自己的 MetricRegistry。我们在创建一个 spring boot 时遇到了一些问题,但是我们的 spring 测试失败了,因为它丢失了。如果你自己创建一个,这个问题就会消失。只需将其添加到您的@Configuration课程之一

@Bean
public MetricRegistry metricRegistry() {
    // explicitly register a metricRegistry so we can run our spring tests without relying on spring boot creating
    // one for us. Spring boot seems to do the right thing either way.
    // Used to register codahale metrics from MetricSet implementing beans.
    return new MetricRegistry();
}

有了这一切,Spring boot 做了正确的事情并将指标添加到 /metrics。

于 2017-05-10T09:16:27.267 回答