Java / Gradle

Consul and the Micronaut Framework - Microservices Service Discovery

Use Consul service discovery to expose your Micronaut applications.

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create three microservices and register them with Consul Service discovery.

Consul is a distributed service mesh to connect, secure, and configure services across any runtime platform and public or private cloud.

You will discover how the Micronaut framework eases Consul integration.

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 App

Let’s describe the microservices you will build through the guide.

  • bookcatalogue - It returns a list of books. It uses a domain consisting of a book name and an ISBN.

  • bookinventory - It exposes an endpoint to check whether a book has sufficient stock to fulfill an order. It uses a domain consisting of a stock level and an ISBN.

  • bookrecommendation - It consumes previous services and exposes an endpoint that recommends book names that are in stock.

Initially, we will hard-code the service addresses in the bookcatalogue service.

hardcoded

As shown in the previous image, the bookcatalogue hardcodes references to its collaborators.

In the second part of this guide, we will use a discovery service.

Note

About registration patterns

We will use a self‑registration pattern. Thus, each service instance is responsible for registering and deregistering itself with the service registry. Also, if required, a service instance sends heartbeat requests to prevent its registration from expiring.

Services register when they start up:

discovery service registration

We will use client‑side service discovery. Clients query the service registry, select an available instance, and make a request.

discovery service flow

Catalogue Microservice

Create the bookcatalogue microservice using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app --features=discovery-consul,management,graalvm example.micronaut.bookcatalogue --build=gradle --lang=java
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.

If you use Micronaut Launch, select Micronaut Application as application type and add the discovery-consul, management, and graalvm features.

The previous command creates a directory named bookcatalogue and a Micronaut application inside it with default package example.micronaut.

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.

Create a BooksController class to handle incoming HTTP requests into the bookcatalogue microservice:

bookcatalogue/java/src/main/java/example/micronaut/BooksController.java

The previous controller responds with a List<Book>. Create the Book POJO:

bookcatalogue/java/src/main/java/example/micronaut/Book.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.serde.annotation.Serdeable;

import jakarta.validation.constraints.NotBlank;
import java.util.Objects;

@Serdeable
public class Book {

    @NonNull
    @NotBlank
    private final String isbn;

    @NonNull
    @NotBlank
    private final String name;

    public Book(@NonNull @NotBlank String isbn,
                @NonNull @NotBlank String name) {
        this.isbn = isbn;
        this.name = name;
    }

    @NonNull
    public String getIsbn() {
        return isbn;
    }

    @NonNull
    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Book book = (Book) o;
        return Objects.equals(isbn, book.isbn) && Objects.equals(name, book.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(isbn, name);
    }
}

Write a test:

bookcatalogue/java/src/test/java/example/micronaut/BooksControllerTest.java

Edit application.properties

bookcatalogue/src/main/resources/application.properties

Modify the Application class to use dev as a default environment:

The Micronaut framework supports the concept of one or many default environments. A default environment is one that is only applied if no other environments are explicitly specified or deduced.

bookcatalogue/java/src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.runtime.Micronaut;

import static io.micronaut.context.env.Environment.DEVELOPMENT;

public class Application {

    public static void main(String[] args) {
        Micronaut.build(args)
                .mainClass(Application.class)
                .defaultEnvironments(DEVELOPMENT)
                .start();
    }
}

Create src/main/resources/application-dev.properties. The Micronaut framework applies this configuration file only for the dev environment.

bookcatalogue/src/main/resources/application-dev.properties

Create a file named application-test.properties which is used in the test environment:

bookcatalogue/src/test/resources/application-test.properties
consul.client.registration.enabled=false

Run the unit test:

bookcatalogue
./gradlew test

Inventory Microservice

Create the bookinventory microservice using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app --features=discovery-consul,management,graalvm example.micronaut.bookinventory --build=gradle --lang=java
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.

If you use Micronaut Launch, select Micronaut Application as application type and add the discovery-consul, management, and graalvm features.

The previous command creates a directory named bookinventory and a Micronaut application inside it with default package example.micronaut.

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.

Create a Controller:

bookinventory/java/src/main/java/example/micronaut/BooksController.java

Create the POJO used by the controller:

bookinventory/java/src/main/java/example/micronaut/BookInventory.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.serde.annotation.Serdeable;

import jakarta.validation.constraints.NotBlank;
import java.util.Objects;

@Serdeable
public class BookInventory {

    @NonNull
    @NotBlank
    private final String isbn;

    private final int stock;

    public BookInventory(@NonNull @NotBlank String isbn,
                         int stock) {
        this.isbn = isbn;
        this.stock = stock;
    }

    @NonNull
    public String getIsbn() {
        return isbn;
    }

    public int getStock() {
        return stock;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        BookInventory that = (BookInventory) o;
        return stock == that.stock && Objects.equals(isbn, that.isbn);
    }

    @Override
    public int hashCode() {
        return Objects.hash(isbn, stock);
    }
}

Write a test:

bookinventory/java/src/test/java/example/micronaut/BooksControllerTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

import static io.micronaut.http.HttpStatus.NOT_FOUND;
import static io.micronaut.http.HttpStatus.OK;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest
public class BooksControllerTest {

    @Inject
    @Client("/")
    HttpClient httpClient;

    @Test
    public void testBooksController() {
        HttpResponse<Boolean> rsp = httpClient.toBlocking().exchange(
                HttpRequest.GET("/books/stock/1491950358"), Boolean.class);
        assertEquals(OK, rsp.status());
        assertTrue(rsp.body());
    }

    @Test
    public void testBooksControllerWithNonExistingIsbn() {
        HttpClientResponseException thrown = assertThrows(HttpClientResponseException.class, () -> {
            httpClient.toBlocking().exchange(HttpRequest.GET("/books/stock/XXXXX"), Boolean.class);
        });

        assertEquals(NOT_FOUND, thrown.getResponse().getStatus());
    }
}

Edit application.properties

bookinventory/src/main/resources/application.properties

Modify the Application class to use dev as a default environment:

The Micronaut framework supports the concept of one or many default environments. A default environment is one that is only applied if no other environments are explicitly specified or deduced.

bookinventory/java/src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.runtime.Micronaut;

import static io.micronaut.context.env.Environment.DEVELOPMENT;

public class Application {

    public static void main(String[] args) {
        Micronaut.build(args)
                .mainClass(Application.class)
                .defaultEnvironments(DEVELOPMENT)
                .start();
    }
}

Create src/main/resources/application-dev.properties. The Micronaut framework applies this configuration file only for the dev environment.

bookinventory/src/main/resources/application-dev.properties

Create a file named application-test.properties which is used in the test environment:

bookinventory/src/test/resources/application-test.properties
consul.client.registration.enabled=false

Run the unit test:

bookinventory
./gradlew test

Recommendation Microservice

Create the bookrecommendation microservice using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app --features=discovery-consul,management,reactor,graalvm example.micronaut.bookrecommendation --build=gradle --lang=java
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.

If you use Micronaut Launch, select Micronaut Application as application type and add the discovery-consul, management, reactor, and graalvm features.

The previous command creates a directory named bookrecommendation and a Micronaut application inside it with default package example.micronaut.

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.

Create an interface to map operations with bookcatalogue, and a Micronaut Declarative HTTP Client to consume it.

bookrecommendation/java/src/main/java/example/micronaut/BookCatalogueOperations.java
package example.micronaut;

import org.reactivestreams.Publisher;

public interface BookCatalogueOperations {
    Publisher<Book> findAll();
}
bookrecommendation/java/src/main/java/example/micronaut/BookCatalogueClient.java

The client returns a POJO. Create it in the bookrecommendation:

bookrecommendation/java/src/main/java/example/micronaut/Book.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.serde.annotation.Serdeable;

import jakarta.validation.constraints.NotBlank;
import java.util.Objects;

@Serdeable
public class Book {

    @NonNull
    @NotBlank
    private final String isbn;

    @NonNull
    @NotBlank
    private final String name;

    public Book(@NonNull @NotBlank String isbn,
                @NonNull @NotBlank String name) {
        this.isbn = isbn;
        this.name = name;
    }

    @NonNull
    public String getIsbn() {
        return isbn;
    }

    @NonNull
    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Book book = (Book) o;
        return Objects.equals(isbn, book.isbn) && Objects.equals(name, book.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(isbn, name);
    }
}

Create an interface to map operations with bookinventory, and a Micronaut Declarative HTTP Client to consume it.

bookrecommendation/java/src/main/java/example/micronaut/BookInventoryOperations.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import reactor.core.publisher.Mono;

import jakarta.validation.constraints.NotBlank;

public interface BookInventoryOperations {
    Mono<Boolean> stock(@NonNull @NotBlank String isbn);
}
bookrecommendation/java/src/main/java/example/micronaut/BookInventoryClient.java

Create a Controller which injects both clients.

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

The previous controller returns a Publisher<BookRecommendation>. Create the BookRecommendation POJO:

bookrecommendation/java/src/main/java/example/micronaut/BookRecommendation.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.serde.annotation.Serdeable;

import jakarta.validation.constraints.NotBlank;

@Serdeable
public class BookRecommendation {

    @NonNull
    @NotBlank
    private final String name;

    public BookRecommendation(@NonNull @NotBlank String name) {
        this.name = name;
    }

    @NonNull
    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        BookRecommendation that = (BookRecommendation) o;

        return name.equals(that.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

BookCatalogueClient and BookInventoryClient will fail to consume the bookcatalogue and bookinventory during the tests phase.

Using the @Fallback annotation, you can declare a fallback implementation of a client that will be picked up and used once all possible retries have been exhausted.

Create @Fallback alternatives in the test classpath.

bookrecommendation/java/src/test/java/example/micronaut/BookInventoryClientStub.java
bookrecommendation/java/src/test/java/example/micronaut/BookCatalogueClientStub.java
package example.micronaut;

import io.micronaut.context.annotation.Requires;
import io.micronaut.retry.annotation.Fallback;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;

import static io.micronaut.context.env.Environment.TEST;

@Requires(env = TEST)
@Fallback
@Singleton
public class BookCatalogueClientStub implements BookCatalogueOperations {

    @Override
    public Publisher<Book> findAll() {
        Book buildingMicroservices = new Book("1491950358", "Building Microservices");
        Book releaseIt = new Book("1680502395", "Release It!");
        return Flux.just(buildingMicroservices, releaseIt);
    }
}

Write a test:

bookrecommendation/java/src/test/java/example/micronaut/BookControllerTest.java
package example.micronaut;

import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

@MicronautTest
public class BookControllerTest {

    @Inject
    @Client("/")
    HttpClient client;

    @DisabledIfEnvironmentVariable(named = "CI", matches = "true")
    @Test
    public void testRetrieveBooks() {
        List<BookRecommendation> books = client.toBlocking()
                .retrieve(HttpRequest.GET("/books"), Argument.listOf(BookRecommendation.class));
        assertEquals(1, books.size());
        assertEquals("Building Microservices", books.get(0).getName());
    }
}

Edit application.properties

bookrecommendation/src/main/resources/application.properties

Modify the Application class to use dev as a default environment:

The Micronaut framework supports the concept of one or many default environments. A default environment is one that is only applied if no other environments are explicitly specified or deduced.

bookrecommendation/java/src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.runtime.Micronaut;

import static io.micronaut.context.env.Environment.DEVELOPMENT;

public class Application {

    public static void main(String[] args) {
        Micronaut.build(args)
                .mainClass(Application.class)
                .defaultEnvironments(DEVELOPMENT)
                .start();
    }
}

Create src/main/resources/application-dev.properties. The Micronaut framework applies this configuration file only for the dev environment.

bookrecommendation/src/main/resources/application-dev.properties

Create a file named application-test.properties which is used in the test environment:

bookrecommendation/src/test/resources/application-test.properties
consul.client.registration.enabled=false

Run the unit test:

bookrecommendation
./gradlew test

Running the application

Run bookcatalogue microservice:

bookcatalogue
./gradlew run
14:28:34.034 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 499ms. Server Running: http://localhost:8081

Run bookinventory microservice:

bookinventory
./gradlew run
14:31:13.104 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 506ms. Server Running: http://localhost:8082

Run bookrecommendation microservice:

bookrecommendation
./gradlew run
14:31:57.389 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 523ms. Server Running: http://localhost:8080

You can run a cURL command to test the whole application:

curl http://localhost:8080/books
[{"name":"Building Microservices"}]

Consul and the Micronaut framework

Install Consul via Docker

The quickest way to start using Consul is via Docker:

docker run -p 8500:8500 consul

The following screenshots show how to install/run Consul via Kitematic, a UI for Docker.

kitematic consul 1

Configure ports:

kitematic consul 2

Book Catalogue

Append the following snippet to the bookcatalogue service application.properties:

bookcatalogue/src/main/resources/application.properties
consul.client.registration.enabled=true
consul.client.defaultZone=${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}

This configuration registers a Micronaut application with Consul with minimal configuration. Discover a more complete list of configuration options at ConsulConfiguration.

Book Inventory

Modify the application.properties of the bookinventory application with the following snippet:

bookinventory/src/main/resources/application.properties
consul.client.registration.enabled=true
consul.client.defaultZone=${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}

Book Recommendation

Append the following snippet to the bookrecommendation service application.properties:

bookrecommendation/src/main/resources/application.properties
consul.client.registration.enabled=true
consul.client.defaultZone=${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}

Modify BookInventoryClient and BookCatalogueClient to use the service id instead of a hard-coded URL.

bookrecommendation/java/src/main/java/example/micronaut/BookCatalogueClient.java
bookrecommendation/java/src/main/java/example/micronaut/BookInventoryClient.java

Running the App

Run bookcatalogue microservice:

bookcatalogue
./gradlew run
14:28:34.034 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 499ms. Server Running: http://localhost:8081
14:28:34.084 [nioEventLoopGroup-1-3] INFO  i.m.d.registration.AutoRegistration - Registered service [bookcatalogue] with Consul

Run bookinventory microservice:

bookinventory
./gradlew run
14:31:13.104 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 506ms. Server Running: http://localhost:8082
14:31:13.154 [nioEventLoopGroup-1-3] INFO  i.m.d.registration.AutoRegistration - Registered service [bookinventory] with Consul

Run bookrecommendation microservice:

bookrecommendation
./gradlew run
14:31:57.389 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 523ms. Server Running: http://localhost:8080
14:31:57.439 [nioEventLoopGroup-1-3] INFO  i.m.d.registration.AutoRegistration - Registered service [bookrecommendation] with Consul

Consul comes with a HTML UI. Open http://localhost:8500/ui in your browser.

You will see the services registered in Consul:

consului

You can run a cURL command to test the whole application:

curl http://localhost:8080/books
[{"name":"Building Microservices"}]

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 Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle

Start the native executables for the three microservices and run the same curl request as before to check that everything works with GraalVM.

Next Steps

Read more about Consul support in the Micronaut framework.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

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).