Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send string messages to Apache Kafka in a spring boot application.
In order to learn how to create a spring boot project, refer to this article.
The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. And also, java allows explicit typecasting where one type of variable can be forcibly converted into other. For example, the same string message can further be converted into an int or a float if the string consists of only numbers and it needs to be used for some computation. The following steps can be followed in order to publish a string message to Apache Kafka:
- Go to spring initializr and create a starter project with following dependencies:
- Spring Web
- Spring for Apache Kafka
- Open the project in an IDE and sync the dependencies. Now create a new class Controller with the annotation @RestController. This class handles all the RESTful routes.
- In this class, create a GET API and initialize KafkaTemplate with parameter as string. The following is the implementation of the class:
// Java program to implement the
// controller for the spring
String TOPIC =
// Implementing a GET method
) String message)
"Message Published on Kafka !"
- Start zookeeper and Kafka server. Now we need to create a new topic with the name gfg. To do so, open a new command prompt window and change directory to the Kafka directory.
- Now create a new topic using the command given below:
For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name
For Windows: .\bin\windows\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name
- Now to see the messages on the Kafka server in the real-time, use the command below:
For MAC and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginning
For Windows: .\bin\windows\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning
- Run the application and call the API as:
Note: If a different port has been used, then replace the port with 8080.