![]() |
VOOZH | about |
Apache Kafka is widely used for real-time data streaming, and Spring Boot makes it easy to integrate Kafka into Java applications. This article demonstrates how to consume JSON messages in a Spring Boot application and process them efficiently using Kafka consumers.
Follow these steps to implement JSON message consumption in Apache Kafka using a Spring Boot application.
Create a Spring Boot project using Spring Initializr and
Since the application will consume student details in JSON format, create a Student model class.
Create a configuration class named Config and annotate it with @Configuration and @EnableKafka.
Create a service class that listens for incoming messages from Kafka.
Before running the Spring Boot application, start ZooKeeper and the Kafka broker.
Create a topic named JsonTopic.
For macOS/Linux
bin/kafka-topics.sh --create \
--zookeeper localhost:2181 \
--replication-factor 1 \
--partitions 1 \
--topic JsonTopic
For Windows
.\bin\windows\kafka-topics.bat --create ^
--zookeeper localhost:2181 ^
--replication-factor 1 ^
--partitions 1 ^
--topic JsonTopic
Open a new terminal and run the Kafka producer console.
For macOS/Linux
bin/kafka-console-producer.sh \
--broker-list localhost:9092 \
--topic JsonTopic
For Windows
.\bin\windows\kafka-console-producer.bat ^
--broker-list localhost:9092 ^
--topic JsonTopic
Start the Spring Boot application.
Now enter JSON data in the Kafka producer console:
{
"id": 101,
"firstName": "John",
"lastName": "Doe"
}
Press Enter to send the message.
New Entry: Student{
id=101,
firstName='John',
lastName='Doe'
}
The JSON message is automatically deserialized into a Student object and displayed on the console.