DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java

Trending

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Restful Java Metering by Dropwizard Metrics

Restful Java Metering by Dropwizard Metrics

Dropwizard has taken the Java world by storm with it's ease of use and great functionality. The metrics library is particularly powerful for anyone wanting to measure statistics in their Java applications.

By 
Thamizh Arasu user avatar
Thamizh Arasu
·
May. 10, 16 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
21.7K Views

Join the DZone community and get the full member experience.

Join For Free

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.

<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-core</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-jersey2</artifactId>
    <version>3.1.0</version>
</dependency>


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,

public class RestSkolApplication extends ResourceConfig {
    private static final Logger logger = LogManager.getLogger(RestSkolApplication.class);
    private Set<Class<?>> classes = new HashSet<Class<?>>();

    public RestSkolApplication() {
        initializeApplication();
    }

    private void initializeApplication() {
        registerListeners(); // Register listeners
    }

    private void registerListeners() {
        final MetricRegistry metricRegistry = new MetricRegistry();
        register(new InstrumentedResourceMethodApplicationListener(metricRegistry));
        ConsoleReporter.forRegistry(metricRegistry)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build()
                .start(1, TimeUnit.MINUTES);
        logger.info("Console reporter is enabled successfully!");
    }
}


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:

@Path("books")
public class BookResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response getAllBooks() {
        System.out.println("Get all books resource is called");
        final List<Book> books = BookDataStore.getInstance().getBooks();
        return Response.ok()
                .entity(books)
                .build();
    }

    @Path("{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public Response getBook(@PathParam("id") String id) {
        final Book book = BookDataStore.getInstance().getBook(id);
        return Response.ok()  // (Response code)
                .entity(book) // (response value)
                .build();
    }
}


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:

-- Timers ----------------------------------------------------------------------
com.cloudskol.restskol.resources.BookResource.getAllBooks
             count = 5
         mean rate = 0.08 calls/second
     1-minute rate = 0.04 calls/second
     5-minute rate = 0.01 calls/second
    15-minute rate = 0.01 calls/second
               min = 0.09 milliseconds
               max = 0.23 milliseconds
              mean = 0.13 milliseconds
            stddev = 0.05 milliseconds
            median = 0.11 milliseconds
              75% <= 0.12 milliseconds
              95% <= 0.23 milliseconds
              98% <= 0.23 milliseconds
              99% <= 0.23 milliseconds
            99.9% <= 0.23 milliseconds
com.cloudskol.restskol.resources.BookResource.getBook
             count = 2
         mean rate = 0.03 calls/second
     1-minute rate = 0.02 calls/second
     5-minute rate = 0.01 calls/second
    15-minute rate = 0.00 calls/second
               min = 0.42 milliseconds
               max = 14.78 milliseconds
              mean = 7.44 milliseconds
            stddev = 7.17 milliseconds
            median = 0.42 milliseconds
              75% <= 14.78 milliseconds
              95% <= 14.78 milliseconds
              98% <= 14.78 milliseconds
              99% <= 14.78 milliseconds
            99.9% <= 14.78 milliseconds


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

Metric (unit) REST Web Protocols Java (programming language)

Published at DZone with permission of Thamizh Arasu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building a REST Service That Collects HTML Form Data Using Netbeans, Jersey, Apache Tomcat, and Java
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Aggregating REST APIs Calls Using Apache Camel
  • Choosing a Library to Build a REST API in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!