![]() |
VOOZH | about |
Apache Kafka is a publish-subscribe messaging queue used for real-time streams of data. A messaging queue lets you send messages between processes, applications, and servers. In this article we will see how to send string messages from apache kafka to the console of a spring boot application.
Approach:
Step 1: Go to spring initializr and create a starter project with following dependency:
Note: We can also create a maven project and add the following code to pom.xml file.
Step 2: Open the project in an IDE and sync the dependencies. Now create a new class Config and add annotations @Configuration and @EnableKafka.
Step 3: Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with String object.
Step 4: Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console.
Step 5: Start zookeeper and then kafka server using the command below.
For windows:
.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties
.\bin\windows\kafka-server-start.bat .\config\server.properties
For mac and linux:
bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties
Step 6: Now we need to create a new topic with the name StringProducer. To do so, open a new command prompt window and change directory to the kafka directory. 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
Step 7: Now to run kafka producer console, use the command below:
// For Mac and Linux
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Kafka_Example
// For Windows
.\bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic Kafka_Example
Step 7: Run the application and type message on kafka producer and press enter.
Output:
Here type a message in string format on kafka producer
>Hello >Welcome to GeeksForGeeks
Output: