首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Spring Boot中使用dropwizards注解

在Spring Boot中使用dropwizards注解
EN

Stack Overflow用户
提问于 2015-12-28 17:58:32
回答 2查看 5K关注 0票数 1

我打算使用提供的@Timed注释,而不是通过将代码插入到每个感兴趣的方法中进行测量。但是这些指标没有显示任何相应的值:

这是我的代码,想法是将包含的SQL的执行时间放入指标中。

代码语言:javascript
复制
@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( ...
    }
}

@Timed没有出现的问题可能是因为Spring Boot only supports Counter and Gauge

但是@Gauge@Metered@Counted也不能工作。

为了至少让Spring Boot支持的那些指标注释工作,我还缺少什么?(在我的测试中是1.3.1)

EN

回答 2

Stack Overflow用户

发布于 2016-02-08 16:24:24

您可能希望了解一下http://www.ryantenney.com/metrics-spring/

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

票数 2
EN

Stack Overflow用户

发布于 2017-05-10 17:16:27

我最终没有使用注释,只是在我想要检测的bean上实现了MetricSet。特别是在使用计时器时,使用计时器并不是那么困难。

代码语言:javascript
复制
@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类中

代码语言:javascript
复制
@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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34491293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档