Java / Maven

Collect Metrics with Micronaut

Learn how to collect standard and custom metrics with the Micronaut framework.

Burt Beckwith
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

We’ll use Micronaut Micrometer to expose application metric data with Micrometer.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=micrometer-annotation,data-jdbc,flyway,validation,http-client,graalvm \
    --build=maven \
    --lang=java \
    --test=junit
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add micrometer-annotation, data-jdbc, flyway, validation, http-client, and graalvm features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Metrics Configuration

Several groups of metrics are enabled by default. These include system metrics (JVM info, uptime, etc.), as well as metrics tracking web requests, DataSource activity, and others. Overall metrics can be enabled or disabled, and groups can be individually enabled or disabled in configuration.

Add the following to application.properties:

src/main/resources/application.properties

Custom Metrics

If the built-in metrics aren’t enough, you can easily add custom metrics with the following annotations.

@Timed

Creates a Timer metric that contains the total time, max time, and count.

@Counted

Creates a Counter metric that only contains a count.

If you want to create your own gauge, you can inject io.micrometer.core.instrument.MeterRegistry to your bean.

Data Source Metrics

DataSource metrics are enabled by default if you use HikariCP (the default), Tomcat JDBC, or the Commons DBCP connection pool.

Database Migration with Flyway

We need a way to create the database schema. For that, we use Micronaut integration with Flyway.

Flyway automates schema changes, significantly simplifying schema management tasks, such as migrating, rolling back, and reproducing in multiple environments.

Add the following snippet to include the necessary dependencies:

pom.xml
<dependency>
    <groupId>io.micronaut.flyway</groupId>
    <artifactId>micronaut-flyway</artifactId>
    <scope>compile</scope>
</dependency>

We will enable Flyway in the Micronaut configuration file and configure it to perform migrations on one of the defined data sources.

src/main/resources/application.properties
Note
Configuring multiple data sources is as simple as enabling Flyway for each one. You can also specify directories that will be used for migrating each data source. Review the Micronaut Flyway documentation for additional details.

Flyway migration will be automatically triggered before your Micronaut application starts. Flyway will read migration commands in the resources/db/migration/ directory, execute them if necessary, and verify that the configured data source is consistent with them.

Create the following migration files with the database schema creation:

src/main/resources/db/migration/V1__schema.sql
DROP TABLE IF EXISTS book;

CREATE TABLE book (
    id    BIGINT GENERATED BY DEFAULT AS IDENTITY,
    name  VARCHAR(255) NOT NULL,
    isbn  VARCHAR(255) NOT NULL UNIQUE
);

During application startup, Flyway will execute the SQL file and create the schema needed for the application.

Domain

Create a Book domain class that uses Micronaut Data JDBC:

java/src/main/java/example/micronaut/Book.java

BookRepository

Next, create the BookRepository interface to define database operations. Micronaut Data will implement the interface at compilation time:

java/src/main/java/example/micronaut/BookRepository.java

Data populator class

Create a DataPopulator class to create some example database entries when the application starts:

java/src/main/java/example/micronaut/DataPopulator.java

BookController

Create BookController to access Book instances (and trigger JDBC metric data):

java/src/main/java/example/micronaut/BookController.java

Custom Metrics

To see custom metrics in action, create a service that periodically retrieves the current Bitcoin price in USD using REST.

Model

We’ll need a data class to represent the REST response. Create the BitcoinPrice class:

java/src/main/java/example/micronaut/crypto/BitcoinPrice.java

Kucoin Declarative HTTP Client

Create a declarative Micronaut HTTP Client interface that will be implemented at compile time:

java/src/main/java/example/micronaut/crypto/PriceClient.java

HTTP Service Configuration

Modify application.properties to configure the URL for the kucoin Service ID:

src/main/resources/application.properties

Service

Create a CryptoService class that uses PriceClient and updates three custom meters:

java/src/main/java/example/micronaut/crypto/CryptoService.java

Testing the Application

Create the src/test/resources/application-test.properties configuration file for tests.

src/test/resources/application-test.properties

Create a test class to verify metrics functionality:

java/src/test/java/example/micronaut/MetricsTest.java

Create an additional test class to verify the custom metrics:

java/src/test/java/example/micronaut/CryptoUpdatesTest.java
package example.micronaut;

import example.micronaut.crypto.CryptoService;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.annotation.Requires;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.runtime.server.EmbeddedServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import java.util.Collections;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

@TestInstance(PER_CLASS)
public class CryptoUpdatesTest {

    EmbeddedServer embeddedServer;
    EmbeddedServer kucoinEmbeddedServer;

    @BeforeAll
    void beforeAll() {

        kucoinEmbeddedServer = ApplicationContext.run(EmbeddedServer.class,
                Collections.singletonMap("spec.name", "MetricsTestKucoin"));

        embeddedServer = ApplicationContext.run(EmbeddedServer.class,
                Collections.singletonMap("micronaut.http.services.kucoin.url", "http://localhost:" + kucoinEmbeddedServer.getPort()));
    }

    @AfterAll
    void afterAll() {
        embeddedServer.close();
        kucoinEmbeddedServer.close();
    }

    @Test
    void testCryptoUpdates() {
        CryptoService cryptoService = embeddedServer.getApplicationContext().getBean(CryptoService.class);
        MeterRegistry meterRegistry = embeddedServer.getApplicationContext().getBean(MeterRegistry.class);

        Counter counter = meterRegistry.counter("bitcoin.price.checks");
        Timer timer = meterRegistry.timer("bitcoin.price.time");

        assertEquals(0, counter.count(), 0.000001);
        assertEquals(0, timer.totalTime(MILLISECONDS));

        int checks = 3;

        for (int i = 0; i < checks; i++) {
            cryptoService.updatePrice();
        }

        assertEquals(checks, counter.count(), 0.000001);
        assertTrue(timer.totalTime(MILLISECONDS) > 0);
    }

    @Requires(property = "spec.name", value = "MetricsTestKucoin")
    @Controller
    static class MockKucoinController {
        private static final String RESPONSE = """
                {
                "code":"200000",
                   "data":{
                      "time":1654865889872,
                      "sequence":"1630823934334",
                      "price":"29670.4",
                      "size":"0.00008436",
                      "bestBid":"29666.4",
                      "bestBidSize":"0.16848947",
                      "bestAsk":"29666.5",
                      "bestAskSize":"2.37840044"
                   }
                }""";

        @Get("/api/v1/market/orderbook/level1")
        String latest(@QueryValue String symbol) {
            return RESPONSE;
        }
    }
}

The previous test creates two Micronaut embedded servers. One mocks the kucoin API, the other is our application. The test uses @Requires to conditionally load a controller only for the kucoin bean context. We used an identifier with @Client, which makes it easy to point our HTTP client to the mock server.

Running the tests

To run the tests:

./mvnw test

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

Alternatively, to make the Bitcoin price update occur more frequently to see the effects on metrics, start the application with a config override to update every five seconds:

./mvnw mn:run -Dmn.appArgs="-crypto.updateFrequency=5s"

You can retrieve a list of known metrics using cURL:

curl localhost:8080/metrics

The response should look like this:

{
  "names": [
    "bitcoin.price.checks",
    "bitcoin.price.latest",
    "bitcoin.price.time",
    "executor",
    "executor.active",
    "executor.completed",
    "executor.pool.core",
    "executor.pool.max",
    "executor.pool.size",
    "executor.queue.remaining",
    "executor.queued",
    "hikaricp.connections",
    "hikaricp.connections.acquire",
    "hikaricp.connections.active",
    ...
    "jvm.threads.peak",
    "jvm.threads.states",
    "logback.events",
    "process.cpu.usage",
    "process.files.max",
    "process.files.open",
    "process.start.time",
    "process.uptime",
    "system.cpu.count",
    "system.cpu.usage",
    "system.load.average.1m"
  ]
}

After the application has been running for a bit and has made a few Bitcoin price checks, we can view the related metric values:

curl localhost:8080/metrics/bitcoin.price.latest
{
  "measurements": [{ "statistic": "VALUE", "value": 29659.0 } ],
  "name": "bitcoin.price.latest"
}
curl localhost:8080/metrics/bitcoin.price.checks
{
  "measurements": [{ "statistic": "COUNT", "value": 5.0 } ],
  "name": "bitcoin.price.checks"
}
curl localhost:8080/metrics/bitcoin.price.time
{
  "baseUnit": "seconds",
  "measurements": [
    { "statistic": "COUNT",      "value": 5.0 },
    { "statistic": "TOTAL_TIME", "value": 2.525546791 },
    { "statistic": "MAX",        "value": 0.851958216 }
  ],
  "name": "bitcoin.price.time"
}

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.

Note
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

GraalVM Installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 25
sdk install java 25.0.2-graalce

Native Executable Generation

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:

pom.xml

Start the native image and run the cURL commands above to see that the application works the same way as before, with faster startup and response times.

Next Steps

In combination with the /metrics endpoint, you often want to register a specific type of reporter. See the Micronaut Micrometer documentation to learn about the supported libraries for reporting metrics.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).