Kafka and the Micronaut Framework - Event-Driven Applications
Use Kafka to communicate between your Micronaut applications.
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
In this guide, we will create two microservices that will use Kafka to communicate with each other in an asynchronous and decoupled way.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE
-
JDK 17 or greater installed with
JAVA_HOMEconfigured appropriately -
Docker and Docker Compose installed if you will be running Kafka in Docker, and for running tests.
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.
-
Download and unzip the source
Writing the application
Let’s describe the microservices you will build through the guide.
-
books- It returns a list of books. It uses a domain consisting of a book name and ISBN. It also publishes a message in Kafka every time a book is accessed. -
analytics- It connects to Kafka to update the analytics for every book (a counter). It also exposes an endpoint to get the analytics.
Books Microservice
Create the books microservice using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app --features=kafka,reactor,graalvm,serialization-jackson example.micronaut.books --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 kafka, reactor, graalvm, and serialization-jackson features.
The previous command creates a directory named books and a Micronaut application inside it with default package example.micronaut.
In addition to the dependencies added by the above features, we also need a test dependency for the Awaitility library:
testImplementation("org.awaitility:awaitility:@awaitilityVersion@")Create a Book POJO:
package example.micronaut;
import io.micronaut.core.annotation.Creator;
import io.micronaut.serde.annotation.Serdeable;
import java.util.Objects;
@Serdeable
public class Book {
private final String isbn;
private final String name;
@Creator
public Book(String isbn, String name) {
this.isbn = isbn;
this.name = name;
}
public String getIsbn() {
return isbn;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Book{" +
"isbn='" + isbn + '\'' +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book other = (Book) o;
return Objects.equals(isbn, other.isbn) &&
Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(isbn, name);
}
}To keep this guide simple there is no database persistence - BookService keeps the list of books in memory:
package example.micronaut;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Singleton
public class BookService {
private final List<Book> bookStore = new ArrayList<>();
@PostConstruct
void init() {
bookStore.add(new Book("1491950358", "Building Microservices"));
bookStore.add(new Book("1680502395", "Release It!"));
bookStore.add(new Book("0321601912", "Continuous Delivery"));
}
public List<Book> listAll() {
return bookStore;
}
public Optional<Book> findByIsbn(String isbn) {
return bookStore.stream()
.filter(b -> b.getIsbn().equals(isbn))
.findFirst();
}
}Create a BookController class to handle incoming HTTP requests to the books microservice:
Analytics Microservice
Create the analytics microservice using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app --features=kafka,graalvm,serialization-jackson example.micronaut.analytics --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 kafka and graalvm features.
Create a Book POJO:
package example.micronaut;
import io.micronaut.core.annotation.Creator;
import io.micronaut.serde.annotation.Serdeable;
import java.util.Objects;
@Serdeable
public class Book {
private final String isbn;
private final String name;
@Creator
public Book(String isbn, String name) {
this.isbn = isbn;
this.name = name;
}
public String getIsbn() {
return isbn;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Book{" +
"isbn='" + isbn + '\'' +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book other = (Book) o;
return Objects.equals(isbn, other.isbn) &&
Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(isbn, name);
}
}|
Note
|
This Book POJO is the same as the one in the books microservice. In a real application this would be in a shared library but to keep things simple we’ll just duplicate it.
|
Create a BookAnalytics POJO:
package example.micronaut;
import io.micronaut.core.annotation.Creator;
import io.micronaut.serde.annotation.Serdeable;
@Serdeable
public class BookAnalytics {
private final String bookIsbn;
private final long count;
@Creator
public BookAnalytics(String bookIsbn, long count) {
this.bookIsbn = bookIsbn;
this.count = count;
}
public String getBookIsbn() {
return bookIsbn;
}
public long getCount() {
return count;
}
}To keep this guide simple there is no database persistence - AnalyticsService keeps book analytics in memory:
Write a test for AnalyticsService:
package example.micronaut;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import jakarta.inject.Inject;
import java.util.List;
@MicronautTest
class AnalyticsServiceTest {
@Inject
AnalyticsService analyticsService;
@Test
void testUpdateBookAnalyticsAndGetAnalytics() {
Book b1 = new Book("1491950358", "Building Microservices");
Book b2 = new Book("1680502395", "Release It!");
analyticsService.updateBookAnalytics(b1);
analyticsService.updateBookAnalytics(b1);
analyticsService.updateBookAnalytics(b1);
analyticsService.updateBookAnalytics(b2);
List<BookAnalytics> analytics = analyticsService.listAnalytics();
assertEquals(2, analytics.size());
assertEquals(3, findBookAnalytics(b1, analytics).getCount());
assertEquals(1, findBookAnalytics(b2, analytics).getCount());
}
private BookAnalytics findBookAnalytics(Book b, List<BookAnalytics> analytics) {
return analytics
.stream()
.filter(bookAnalytics -> bookAnalytics.getBookIsbn().equals(b.getIsbn()))
.findFirst()
.orElseThrow(() -> new RuntimeException("Book not found"));
}
}Create a Controller to expose the analytics:
|
Note
|
The application doesn’t expose the method |
To run the tests:
./gradlew testModify 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.
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.
Running the application
Start the books microservice:
./gradlew run16:35:55.614 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 576ms. Server Running: http://localhost:8080Start the analytics microservice:
./gradlew run16:35:55.614 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 623ms. Server Running: http://localhost:8081You can use curl to test the application:
curl http://localhost:8080/books[{"isbn":"1491950358","name":"Building Microservices"},{"isbn":"1680502395","name":"Release It!"},{"isbn":"0321601912","name":"Continuous Delivery"}]curl http://localhost:8080/books/1491950358{"isbn":"1491950358","name":"Building Microservices"}curl http://localhost:8081/analytics[]Note that getting the analytics returns an empty list because the applications are not communicating with each other (yet).
Test Resources
When the application is started locally, either under test or while running locally, resolution of the property kafka.bootstrap.servers is detected and the Test Resources service will start a local Kafka docker container, and inject the properties required to use this as the broker.
When running under production, you should replace this property with the location of your production Kafka instance via an environment variable.
KAFKA_BOOTSTRAP_SERVERS=production-server:9092For more information, see the Kafka section of the Test Resources documentation.
Kafka and the Micronaut Framework
Install Kafka
A fast way to start using Kafka is via Docker. Create this docker-compose.yml file:
Start Zookeeper and Kafka (use CTRL-C to stop both):
docker-compose upAlternatively you can install and run a local Kafka instance.
Books Microservice
The generated code will use the Test Resources plugin to start a local Kafka broker inside Docker, and configure the connection URL.
Create Kafka client (producer)
Let’s create an interface to send messages to Kafka. The Micronaut framework will implement the interface at compilation time:
Create Tests
We could use mocks to test the message sending logic between BookController, AnalyticsFilter, and AnalyticsClient, but it’s more realistic to use a running Kafka broker. This is why Test Resources are used to run Kafka inside a Docker container.
Write a test for BookController to verify the interaction with AnalyticsService:
Send Analytics information automatically
Sending a message to Kafka is as simple as injecting AnalyticsClient and calling the updateAnalytics method. The goal is to do it automatically every time a book is returned, i.e., every time there is a call to http://localhost:8080/books/{isbn}.
To achieve this we will create an Http Server Filter.
Create the AnalyticsFilter class:
Analytics Microservice
Create Kafka consumer
Create a new class to act as a consumer of the messages sent to Kafka by the books microservice. The Micronaut framework will implement logic to invoke the consumer at compile time. Create the AnalyticsListener class:
Running the application
Start the books microservice:
./gradlew run16:35:55.614 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 576ms. Server Running: http://localhost:8080Execute a curl request to get one book:
curl http://localhost:8080/books/1491950358{"isbn":"1491950358","name":"Building Microservices"}Start the analytics microservice:
./gradlew run16:35:55.614 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 623ms. Server Running: http://localhost:8081The application will consume and process the message automatically after startup.
Now, use curl to see the analytics:
curl http://localhost:8081/analytics[{"bookIsbn":"1491950358","count":1}]Update the curl command to the books microservice to retrieve other books and repeat the invocations, then re-run the curl command to the analytics microservice to see that the counts increase.
Generate Micronaut Application Native Executables 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.
|
Native Executable Generation
sdk install java 25.0.2-graalFor 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:
sdk install java 25.0.2-graalceTo generate native executables for each application using Gradle, run:
./gradlew nativeCompileThe native executables are created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.
It is possible to customize the name of a native executable or pass additional parameters to GraalVM:
Start the native executables for the two microservices and run the same curl request as before to check that everything works with GraalVM.
Next Steps
Read more about Kafka support in Micronaut framework.
Read more about Test Resources in Micronaut.
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). |