zoukankan      html  css  js  c++  java
  • JAVA Metrics 度量工具使用介绍1

    Java Metric使用介绍1

    Metrics是一个给JAVA提供度量工具的包,在JAVA代码中嵌入Metrics代码,可以方便的对业务代码的各个指标进行监控,同一时候,Metrics可以非常好的跟Ganlia、Graphite结合,方便的提供图形化接口。

             以下简介下Metrics怎样使用。

    Maven地址:

    仅仅须要添加metrics-core就可以使用

        <dependency>
            <groupId>com.yammer.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>2.2.0</version>
        </dependency>

    源文档 <http://metrics.codahale.com/getting-started/>

    以下通过一些測试代码介绍Metrics每一个组件的使用,比較简单,基本看代码就懂了,这里不做过多介绍,请结合http://metrics.codahale.com/getting-started/介绍一起看,这里相当于完好代码。

    Gauges

    最简单的度量指标,每次相当于重置这个值。

    package com.alibaba.cxf.test.metric;
     
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.Metrics;
    import com.yammer.metrics.core.Counter;
    import com.yammer.metrics.core.Gauge;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    /**
     * TODO
     * @author scutshuxue.chenxf
     */
    public class TestGauges {
            public static Queue<String> queue = new LinkedList<String>();
     
            public static void main(String[] args) throws InterruptedException{
                   ConsoleReporter.enable(5,TimeUnit.SECONDS);
     
                   Gauge<Integer>g = Metrics.newGauge(TestGauges.class, "pending-jobs", newGauge<Integer>() {
                       @Override
                       public Integer value() {
                           return queue.size();
                       }
                   });
                   queue.add("ssss");
                   System.out.println(g.value());
                   while(true){
                           Thread.sleep(1000);
                   }
            }
    }


    运行效果例如以下:

    12-12-20 14:48:53==============================================================
    com.alibaba.cxf.test.metric.TestGauges:
      pending-jobs:
        value = 1


    代码中都添加了ConsoleReporter.enable(1, TimeUnit.SECONDS);语句,通过这个命令,能够每秒钟将度量指标打印在屏幕上,理解起来会有更清楚的理解。

    Counter,计数器

    package com.alibaba.cxf.test.metric;
     
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.Metrics;
    import com.yammer.metrics.core.Counter;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    /**
     * TODO
     * @author scutshuxue.chenxf
     */
    public class TestCounter {
     
            private final Counter pendingJobs = Metrics.newCounter(TestCounter.class, "pending-jobs");
            private final Queue<String> queue = new LinkedList<String>();
     
            public void add(Stringstr) {
                pendingJobs.inc();
                queue.offer(str);
            }
     
            public String take() {
                pendingJobs.dec();
                return queue.poll();
            }
            /**
             * TODO
             * @author scutshuxue.chenxf
             * @param args
             * void
             * @throws InterruptedException
             */
            public static void main(String[]args) throws InterruptedException {
                   // TODOAuto-generated method stub
                   TestCounter tc =new TestCounter();
                   ConsoleReporter.enable(1,TimeUnit.SECONDS);
                   while(true){
                           tc.add("1");
                           Thread.sleep(1000);
                   }
            }
     
    }


    效果例如以下:

    12-12-20 14:48:53==============================================================
    com.alibaba.cxf.test.metric.TestGauges:
      pending-jobs:
        value = 1


    Meters

    Meters会将近期1分钟,5分钟,15分钟的TPS(每秒处理的request数)给打印出来,还有全部时间的TPS。

    package com.alibaba.cxf.test.metric;
     
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.Metrics;
    import com.yammer.metrics.core.Meter;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    /**
     * TODO
     * @author scutshuxue.chenxf
     */
    public class TestMeters {
            private static Meter meter = Metrics.newMeter(TestMeters.class, "requests","requests", TimeUnit.SECONDS);
     
            public static void main(String[] args) throws InterruptedException{
                   ConsoleReporter.enable(1,TimeUnit.SECONDS);
                   while(true){
                           meter.mark();
                           meter.mark();
                           Thread.sleep(1000);
                   }
            }
    }


    效果例如以下:

    12-12-20 15:02:50==============================================================
    com.alibaba.cxf.test.metric.TestMeters:
      requests:
                 count = 20
             mean rate = 2.20requests/s
         1-minute rate = 2.00requests/s
         5-minute rate = 2.00requests/s
    15-minute rate = 2.00requests/s


    Histograms 直方图

    最大值,最小值,平均值,方差,中位值,百分比数据,如75%,90%,98%,99%的数据在哪个范围内。

    package com.alibaba.cxf.test.metric;
     
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.Metrics;
    import com.yammer.metrics.core.Histogram;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    /**
     * TODO
     * @author scutshuxue.chenxf
     */
    public class TestHistograms {
            private static Histogram histo = Metrics.newHistogram(TestHistograms.class,"histo-sizes");
     
            /**
             * TODO
             * @author scutshuxue.chenxf
             * @param args
             * void
             * @throws InterruptedException
             */
            public static void main(String[] args) throws InterruptedException {
                   // TODOAuto-generated method stub
                  
                   ConsoleReporter.enable(1,TimeUnit.SECONDS);
                   int i=0;
                   while(true){
                           histo.update(i++);
                           Thread.sleep(1000);
                   }
            }
     
    }


    效果例如以下:

    com.alibaba.cxf.test.metric.TestHistograms:
      histo-sizes:
                   min = 0.00
                   max = 5.00
                  mean = 2.50
                stddev = 1.87
                median = 2.50
                  75% <= 4.25
                  95% <= 5.00
                  98% <= 5.00
                  99% <= 5.00
                99.9% <= 5.00



    Timers

    时间统计

    package com.alibaba.cxf.test.metric;
     
    import java.util.Random;
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.Metrics;
    import com.yammer.metrics.core.Timer;
    import com.yammer.metrics.core.TimerContext;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    /**
     * TODO
     * @author scutshuxue.chenxf
     */
    public class TestTimers {
            private static Timer timer = Metrics.newTimer(TestTimers.class, "responses", TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
            /**
             * TODO
             * @author scutshuxue.chenxf
             * @param args
             * void
             * @throws InterruptedException
             */
            public static voidmain(String[] args) throws InterruptedException {
                   // TODOAuto-generated method stub
                   ConsoleReporter.enable(2,TimeUnit.SECONDS);
                   Random rn = newRandom();
                   timer.time();
                   System.out.println();
                   while(true){
                           TimerContextcontext = timer.time();
                          
                           Thread.sleep(rn.nextInt(1000));
                           context.stop();
                   }
            }
     
    }


    效果例如以下:

    com.alibaba.cxf.test.metric.TestTimers:
      responses:
                 count = 26
             mean rate = 2.15calls/s
         1-minute rate = 1.70calls/s
         5-minute rate = 1.62calls/s
        15-minute rate = 1.61calls/s
                   min = 35.47ms
                   max = 878.76ms
                  mean = 462.50ms
                stddev = 284.91ms
                median = 419.90ms
                  75% <=764.13ms
                  95% <=877.76ms
                  98% <=878.76ms
                  99% <=878.76ms
                99.9% <=878.76ms


    Health Checks

    健康检查,如心跳:

    package com.alibaba.cxf.test.metric;
     
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Random;
    import java.util.concurrent.TimeUnit;
     
    import com.yammer.metrics.HealthChecks;
    import com.yammer.metrics.core.HealthCheck;
    import com.yammer.metrics.reporting.ConsoleReporter;
     
    public class DatabaseHealthCheck extends HealthCheck {
        private static Databasedatabase;
            private static final Map<String, Result> results = HealthChecks.runHealthChecks();
     
        public DatabaseHealthCheck(Databasedatabase) {
           super("database");
            this.database =database;
        }
     
        @Override
        public Result check()throws Exception {
           
            if(database.isConnected()) {
                returnResult.healthy();
            } else {
                return Result.unhealthy("Cannotconnect to database" );
            }
        }
       
        public static void main(String[] args) throws Exception{
            Database db = new Database();
            DatabaseHealthCheck checkHealth = new DatabaseHealthCheck(db);
                   HealthChecks.register(checkHealth);
                  
                   while(true){
                           Map<String,Result> results = HealthChecks.runHealthChecks();
                           for(Entry<String, Result> entry : results.entrySet()) {
                               if (entry.getValue().isHealthy()) {
                                   System.out.println(entry.getKey() +" is healthy");
                               } else {
                                   System.err.println(entry.getKey() +" is UNHEALTHY: " + entry.getValue().getMessage());
                               }
                           }             
                           Thread.sleep(1000);
                   }
        }   
    }
    class Database{
            static Random rn = newRandom();
           
            public booleanisConnected() {
                   // TODOAuto-generated method stub
                   returnrn.nextBoolean();
            }
           
    }


    效果例如以下:

    com.alibaba.cxf.test.metric.TestTimers:
      responses:
                 count = 26
             mean rate = 2.15calls/s
         1-minute rate = 1.70calls/s
         5-minute rate = 1.62calls/s
        15-minute rate = 1.61calls/s
                   min = 35.47ms
                   max = 878.76ms
                  mean = 462.50ms
                stddev = 284.91ms
                median = 419.90ms
                  75% <=764.13ms
                  95% <=877.76ms
                  98% <=878.76ms
                  99% <=878.76ms
                99.9% <=878.76ms


  • 相关阅读:
    对象并不一定都是在堆上分配内存的
    Minor GC、Major GC和Full GC之间的区别
    JAVA内存分配与回收策略
    HotSpot虚拟机对象相关内容
    JAVA运行时数据区域
    Java 的强引用、弱引用、软引用、虚引用
    去哪儿网支付系统架构演进(下篇)
    去哪儿网支付系统架构演进(上)
    心智模式:如何改善我们的心智模式?
    心智模式:心智模式成熟的标志
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4391574.html
Copyright © 2011-2022 走看看