打造可监控的线上应用dropwizard-metrics

dropwizard-metrics是一个强大的Java库,用于深入了解代码在生产环境中的行为。本文介绍了如何设置Maven,使用MetricRegistry注册Gauge、Counter和Timer,以及设计健康检查Health Checks。重点展示了如何配合ConsoleReporter定时输出统计信息。
摘要由CSDN通过智能技术生成

dropwizard-metrics

Metrics is a Java library which gives you unparalleled insight into what your code does in production.
Metrics provides a powerful toolkit of ways to measure the behavior of critical components in your production environment.

Getting Started

Setting Up Maven

<dependencies>
    <dependency>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-core</artifactId>
        <version>${metrics.version}</version>
    </dependency>
</dependencies>

核心组件:MetricRegistry 及核心方法

这样实例化:

final MetricRegistry metrics = new MetricRegistry();

方法签名:
public T register(String name, T metric) throws IllegalArgumentException {…}

注册一个统计量Gauge

举例,要监测一个队列的长度,每次获取该统计量时返回队列长度:

package org.lanqiao.metrics.test;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import org.web2017.test.data.RandomData;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

public class MetricRegistryTest {
   
  // 统计量注册表
  final static MetricRegistry metricRegistry = new MetricRegistry();

  final static Queue queue = new LinkedList();

  public static void main(String[] args) {
    //模拟填充队列
    new Thread( () -> {
      while (true) {
        queue.add( RandomData.randomId() );
        try {
          TimeUnit.SECONDS.sleep( 3 );
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    } ).start();
    //注册一个Gauge
    metricRegistry.register( MetricRegistry.name( MetricRegistryTest.class, "queue","size" ), new Gauge<Integer>() {
      @Override
      public Integer getValue() {
        return queue.size();
      }
    } );

    //向控制台输出报告
    //定义一个ConsoleReporter
    ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值