Working with Apache Kafka using Spring Boot

In the previous tutorials Manage Apache Kafka using KafkaAdmin class of Spring for Apache Kafka and Send messages to Apache Kafka using the KafkaTemplate class of Spring for Apache Kafka, I have guided you on how to work with Apache Kafka using Spring’s Spring for Apache Kafka module. Spring Boot also supports Apache Kafka by automatically configuring the necessary information so that we can easily work with Apache Kafka using Spring. How is it in detail? Let’s find out together in this tutorial!

First, I will create a new Spring Boot project with Spring for Apache Kafka:

for example.

Manage topics

As you know, we will use the KafkaAdmin class to manage topics in Apache Kafka. With the auto-configuration mechanism of Spring Boot, you just need to configure the information of the Apache Kafka server using the following property:

is to be able to ingest the bean of the KafkaAdmin class to use.

For example, if I configure the bean of the NewTopic class:

then when running the application, you will also see a new topic created.

Get topic information using the KafkaAdmin class as follows:

You will see the same result as the previous post:

Send a message to a topic

With the KafkaTemplate class, you just need to configure some additional properties to be able to ingest the bean of the KafkaTemplate class for use:

For example:

Result:

Receive messages

Spring Boot supports the following properties for consumers, which help us easily consume messages from the Apache Kafka server in Spring Boot applications. Specifically as follows:

Just declare these properties, Spring Boot will initialize the bean for the class implementing the KafkaListenerContainerFactory interface and the bean for the ConsumerFactory class.

Now you just need to define the class containing the method annotated with the @KafkaListener annotation. My example is as follows:

The result if I run the application, send a message “Hello World!” to Apache Kafka server using the example in the tutorial Send messages to Apache Kafka using the KafkaTemplate class of Spring for Apache Kafka, is as follows:

Add Comment