Send messages to Apache Kafka using the KafkaTemplate class of Spring for Apache Kafka

I have guided you on how to use the KafkaAdmin class of Spring for Apache Kafka to manage topics in Apache Kafka. To send or delete messages in Apache Kafka Topics in projects using Spring, you can use the KafkaTemplate class of this Spring for Apache Kafka module. How is it in detail? We will find out together in this tutorials!

First, I will create a new Maven project as an example:

Spring for Apache Kafka is declared as follows:

We can initialize the bean of KafkaTemplate in Spring Container as follows:

The parameter when initializing the KafkaTemplate object is the information of Apache Kafka that the application will work with! As you can see, it is the object of the DefaultKafkaProducerFactory class, an implementation of the ProducerFactory interface. We will declare the information of the Apache Kafka server, the classes to serialize the key and value of the Kafka message using this DefaultKafkaProducerFactory class.

There are many overloaded send() methods in the KafkaTemplate class that help us send a message to Apache Kafka, as follows:

You can choose the method you want.

For example, I will use the send() method with 2 parameters: the topic name and the data I want to send. My code is as follows:

Shortened with Lambda Expression would be as follows:

As you can see, the object returned when we call the send() method is a CompletableFuture and the result will be returned asynchronously.

The result when I run this example is as follows:

So we have successfully sent a message to Apache Kafka!

Add Comment