Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - Consume JSON Object From Kafka Topics
Next article icon

Spring Boot - Consume JSON Object From Kafka Topics

Last Updated : 11 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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?

Implementation:

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.

Java
// Java Program to Illustrate Book Class  package com.amiya.kafka.apachekafkaconsumer.Model;  // Class public class Book {      // Class data members     private String bookName;     private String isbn;      // Constructor 1     public Book() {}      // Constructor 2     public Book(String bookName, String isbn)     {         // This keyword refers to         // current instance itself         this.bookName = bookName;         this.isbn = isbn;     }      // Setter     public String getBookName() { return bookName; }      // Setter     public void setBookName(String bookName)     {         this.bookName = bookName;     }      // Setter     public String getIsbn() { return isbn; }      // Setter     public void setIsbn(String isbn) { this.isbn = isbn; } } 

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.

Example

Java
// Java Program to Illustrate Configuration Class  package com.amiya.kafka.apachekafkaconsumer.config;  // Importing required classes import com.amiya.kafka.apachekafkaconsumer.Model.Book; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.support.serializer.JsonDeserializer;  // Annotation @EnableKafka @Configuration  // Class public class KafkaConfig {      @Bean     public ConsumerFactory<String, Book> consumerFactory()     {          // Creating a map of string-object type         Map<String, Object> config = new HashMap<>();          // Adding the Configuration         config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,                    "127.0.0.1:9092");         config.put(ConsumerConfig.GROUP_ID_CONFIG,                    "group_id");         config.put(             ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,             StringDeserializer.class);         config.put(             ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,             JsonDeserializer.class);          // Returning message in JSON format         return new DefaultKafkaConsumerFactory<>(             config, new StringDeserializer(),             new JsonDeserializer<>(Book.class));     }      // Creating a Listener     @Bean     public ConcurrentKafkaListenerContainerFactory<String,                                                    Book>     bookListener()     {         ConcurrentKafkaListenerContainerFactory<             String, Book> factory             = new ConcurrentKafkaListenerContainerFactory<>();         factory.setConsumerFactory(consumerFactory());                                                               return factory;     } } 

Step 4: Create a Consumer file named KafkaConsumer.

File: KafkaConsumer.java 

Java
// Java Program to Illustrate kafka Consumer Class  package com.amiya.kafka.apachekafkaconsumer.consumer;  // Importing required classes import com.amiya.kafka.apachekafkaconsumer.Model.Book; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component;  // Annotation @Component  // Class public class KafkaConsumer {      @KafkaListener(topics = "NewTopic",                    groupId = "group_id",                    containerFactory = "bookListener")      // Method     public void     consume(Book book)     {         // Print statement         System.out.println("message = " + book);     } } 

Step 5: Now we have to do the following things in order to consume messages from Kafka topics with Spring Boot

  1. Run the Apache Zookeeper server
  2. Run the Apache Kafka  server
  3. Send the JSON object from Kafka Topics

Run your Apache Zookeeper server by using this command:

C:\kafka>.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties

Similarly, run your Apache Kafka server by using this command

C:\kafka>.\bin\windows\kafka-server-start.bat .\config\server.properties

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.

server.port=8081

Let's run the Spring boot application inside the ApacheKafkaConsumerApplication file.

Output:

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. 

Output

Next Article
Spring Boot - Consume JSON Object From Kafka Topics

A

AmiyaRanjanRout
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Sending Email via SMTP
    Spring Boot provides the ability to send emails via SMTP using the JavaMail Library. Here we will be illustrating step-by-step guidelines to develop Restful web services that can be used to send emails with or without attachments. In order to begin with the steps, let us first create a Spring Boot p
    5 min read
    Different Ways to Establish Communication Between Spring Microservices
    If you are working with a Spring Boot project which involves multiple microservices, You might have felt the need to communicate from microservice m1 to microservice m2. Depending upon business use-cases, this communication can be of synchronous or asynchronous type. Before digging dip further. Let'
    3 min read
    JSON using Jackson in REST API Implementation with Spring Boot
    When we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client.In this article, we are going to learn the approach that is used
    4 min read
    How to encrypt passwords in a Spring Boot project using Jasypt
    In this article, we will learn how to encrypt data in Spring Boot application config files like application.properties or application.yml. Inside those files, we can encrypt username, password, etc. You often come across developing projects where you have to connect to databases like MongoDB, etc, a
    4 min read
    Containerizing Spring Boot Application
    Java applications, known for their robustness sometimes become difficult to deploy and manage. This is where containerization comes into the picture. Packaging your Java app into a lightweight and self-contained independent unit can provide many benefits to the developers: PortabilityScalabilityFast
    3 min read
    How to Send Images in Spring Boot without using Servlet and Redundant JSP Codes?
    Open IntelliJ IDE and in the Controller section of your project inside the Controller class you need to build the Image serve method. The Image serve method looks like below and as you have to collect the Image response use @GetMapping Annotation to collect the image. ImageHandler Controller Method
    2 min read
    How to Create Todo List API using Spring Boot and MySQL?
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    6 min read
    Spring Boot - Transaction Management Using @Transactional Annotation
    The @Transactional annotation is the metadata used for managing transactions in the Spring Boot application. To configure Spring Transaction, this annotation can be applied at the class level or method level. In an enterprise application, a transaction is a sequence of actions performed by the appli
    9 min read
    Spring Boot - Map Entity to DTO using ModelMapper
    In enterprise applications, we use RESTful services to establish the communication between client and server. The general idea is that the client sends the request to the server and the server responds to that request with some response. Generally, we have three different layers in most of the appli
    8 min read
    Spring Boot | How to consume JSON messages using Apache Kafka
    Apache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences