【监控指标】Dropwizard Metrics使用

  • Post author:
  • Post category:其他




什么是Dropwizard Metrics

Dropwizard Metrics



简单使用



项目引入

mavan引用

<dependencies>
        <!-- https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-core -->
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.2.2</version>
        </dependency>
    </dependencies>



简单用法

count主要用于普通计数

Timer其实才是最常用的统计,集中了Mate和Histogram的功能,可以统计耗时及最小最大值

Mate用于统计TPS

Histogram用于耗时统计

	MetricRegistry registry = new MetricRegistry();
	Counter a = registry.counter("a");
	Counter b = registry.counter("b");
	//A+1
	a.inc();
	//B+3
	b.inc(3);
	System.out.println(a.getCount());//输出1
	System.out.println(b.getCount());//输出3
	//A+5
	a.inc(5);
	System.out.println(a.getCount());//输出6
	System.out.println(b.getCount());//输出3

	Timer timer = registry.timer("timer");
	Timer.Context time = timer.time();
	Thread.sleep(1000);
	Timer.Context time2 = timer.time();
	Thread.sleep(1000);

	System.out.println(time.stop() / 1000000);//输出200X
	//{"max":2037141700,"mean":2.0371417E9,"median":2.0371417E9,"min":2037141700,"stdDev":0.0,"values":[2037141700]}
	//MAX/1000000=2037ms
	Snapshot timerSnapshot = timer.getSnapshot();
	System.out.println(JSONObject.toJSONString(timerSnapshot));
	System.out.println(time2.stop() / 1000000);//输出100X,因为time2比time晚启动
	Snapshot timerSnapshot2 = timer.getSnapshot();
	//{"max":2019807400,"mean":1.6979087764252641E9,"median":1.380802599E9,"min":1380802599,"stdDev":3.194934147055906E8,"values":[1380802599,2019807400]}
	//二个timer的汇总
	System.out.println(JSONObject.toJSONString(timerSnapshot2));


	//meter统计TPS
	Meter meter = registry.meter("request_rate");
	for (int i = 1; i < 5; i++) {
		Thread.sleep(200);
		meter.mark();
	}

	// 返回总次数
	System.out.println(meter.getCount());//调用4次
	// 返回平均速率=总次数/服务运行总时间。即每一秒中有多少次。
	System.out.println(meter.getMeanRate());//单个调用100ms/1000ms约9~10

	//主要可以用于耗时
	Histogram histogram = registry.histogram("histogram");
	for (long i = 1; i < 5; i++) {
		histogram.update(i);
	}
	//{"max":4,"mean":2.5,"median":3.0,"min":1,"stdDev":1.118033988749895,"values":[1,2,3,4]}
	System.out.println(JSONObject.toJSONString(histogram.getSnapshot()));



核心流程

  1. 注册自动上报,定时写入日志

    参考:https://blog.csdn.net/qq330983778/article/details/124678834



版权声明:本文为weixin_40598274原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。