JAVA Metrics Metric Tool Usage Introduction 1

Source: Internet
Author: User

Java Metric Usage Introduction 1

Metrics is a package for Java to provide measurement tools, embedded in Java code Metrics code, you can easily monitor the various indicators of business code, the same time, metrics can be very good with ganlia, graphite combination, Easy to provide graphical interface.

Below is a brief introduction of how metrics is used.

Maven Address:

Just need to add metrics-core to use

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

Source Document < http://metrics.codahale.com/getting-started/ >

The following through some test code to introduce metrics each component of the use, relatively simple, basic look at the code to understand, here do not introduce too much, please combine http://metrics.codahale.com/getting-started/ Introduction to see together, here is equivalent to the good code.

Gauges

The simplest metric is the equivalent of resetting this value each time.

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 Li         Nkedlist<string> (); public static void Main (string[] args) throws interruptedexception{consolereporter.enable (5,timeunit.second                S); 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);  }        }} 


The results of the operation are as follows:

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


Consolereporter.enable (1, timeunit.seconds) is added to the code, and the statement, with this command, is able to print the metrics on the screen every second, with a clearer understanding.

Counter, 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.ne        Wcounter (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 Int Erruptedexception */public static void Main (String[]args) throws Interruptedexception {//T odoauto-generated Method Stub TestcouNter TC =new testcounter ();               Consolereporter.enable (1,timeunit.seconds);                       while (true) {Tc.add ("1");               Thread.Sleep (1000); }        } }


Effects such as the following:

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


Meters

Meters will print out the recent 1-minute, 5-minute, 15-minute TPS (the number of request processed per second) and the TPS for the full time.

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 (testm Eters.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 (+);}}}        


Effects such as the following:

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


histogramsHistogram

Maximum, minimum, average, variance, median, percent data, such as 75%,90%,98%,99% 's data in which range.

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.newhis Togram (Testhistograms.class, "histo-sizes");         /** *         TODO         * @author scutshuxue.chenxf         * @param args         * void         * @throws interruptedexception         */< C8/>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 (+);               }        } }


Effects such as the following:

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

Time statistics

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 (Te        Sttimers.class, "Responses", timeunit.milliseconds,timeunit.seconds); /** * TODO * @author scutshuxue.chenxf * @param args * void * @throws Interruptede Xception */public static voidmain (string[] args) throws Interruptedexception {//Todoauto-g               enerated 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 (); }        } }


Effects such as the following:

Com.alibaba.cxf.test.metric.TestTimers:  Responses:             count =         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

A health check, such as a heartbeat:

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 ()) {Returnres        Ult.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 (); }       }


Effects such as the following:

Com.alibaba.cxf.test.metric.TestTimers:  Responses:             count =         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


JAVA Metrics Metric Tool Usage Introduction 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.