Spring Boot – Consume JSON Object From Kafka Topics
Apache Kafka is a publish-subscribe messaging system. A messaging system lets someone is sending messages between processes, applications, and servers. Broadly Speaking, Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. Applications may connect to this system and transfer a message onto the topic. A message can include any kind of information, from any event on your Personal blog or can be a very simple text message that would trigger any other event. Read more about Kafka here. In this article, Spring Boot Kafka Consumer Example we have discussed how we can consume messages from Kafka topics with Spring Boot. But in a complex program, we need to consume JSON objects from Kafka topics.
Prerequisite: Make sure you have installed Apache Kafka in your local machine. Refer to this article How to Install and Run Apache Kafka on Windows?
Step 1: Go to this link https://start.spring.io/ and create a Spring Boot project. Add the “Spring for Apache Kafka” dependency to your Spring Boot project.
Step 2: Create a simple POJO class named Book inside the Model package. Below is the code for the Book.java file.
Step 3: Create a Configuration file named KafkaConfig. Below is the code for the KafkaConfig.java file. Comments are added inside the code to understand the code in more detail.
Step 4: Create a Consumer file named KafkaConsumer.
Step 5: Now we have to do the following things in order to consume messages from Kafka topics with Spring Boot
- Run the Apache Zookeeper server
- Run the Apache Kafka server
- Send the JSON object from Kafka Topics
Run your Apache Zookeeper server by using this command:
Similarly, run your Apache Kafka server by using this command
Run the following command to send the JSON object from Kafka Topics
C:\kafka>.\bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic NewTopic
Step 6: Now run your spring boot application. Make sure you have changed the port number in the application.properties file.
Let’s run the Spring boot application inside the ApacheKafkaConsumerApplication file.
In the output, one can see when you are sending the JSON object from Kafka Topics it is displayed on the console in real-time.
Please Login to comment...