RESTful Java metering by Dropwizard Metrics

Do it now and make your customer HAPPY

0
1740
RESTful Java Metering
Metering by Dropwizard
Learn on Udemy Today!

We saw how we can do the RESTful Java Metering using Jersey event listeners (Read here) in one of our earlier article.

Here we are going to see how to use Dropwizard Metrics framework to do the metering of our RESTful resource methods. Dropwizard Metrics is using Jersey events listeners internally to achieve this. They have provided nice wrapper and lots of plug-in to gather the performance of each resource methods without much effort.

Ok! Ready…

There are 3 steps involved in-order to achieve this.

  • Metrics dependency in Maven pom
  • Register ‘MetricRegistry’ and ‘ConsoleReporter’ in our resource configuration
  • Inject @Timed or @Metered annotation for resource methods

Maven pom:

Make the following changes in your pom.xml under dependencies,

Since we are going to use Metrics framework inside Jersey (RESTful Java) framework, the second dependency is required. If your rest service implementation is NOT using Jersey framework, then you can ignore the ‘metrics-jersey2’ dependency. This will fetch the required libraries in our application after the sync operation.

Register ‘MetricRegistry’ and ‘ConsoleReporter’:

Both MetricRegistry and ConsoleReporter implementations are coming from Metrics framework. They actually provide the capability to capture the performance of our resource methods and emit the aggregated result in console as a report.

So do the following changes in our ResourceConfig implementation,

The console report will report the performance metrics for every minute. This interval can be configurable. So change the interval based on your need.

@Timed or @Metered annotation:

The final step is to add either @Timed or @Metered annotation in the REST resource methods like below,

Here I have used @Metered annotation whereas you can use @Timed annotation as well to track the performance numbers. These 2 annotations are provided by Metrics framework.

Good Job!

When you compile and run the application you will see the following output in your console,

First resource has been requested for 5 times and second resource has been requested for 2 times.

Dropwizard Metrics is a great tool for measuring performance of our REST service methods. By watching the numbers carefully we can address many performance problems during the development phase itself!

I hope you have enjoyed reading this article. Please share this with your friends and share your comments or feedback below.

All the code samples are available under https://github.com/cloudskol/restskol