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 Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Spring Boot - Start/Stop a Kafka Listener Dynamically
Next article icon

Spring Boot - Start/Stop a Kafka Listener Dynamically

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In a Spring Boot application, Kafka Listeners start automatically once the application launches and they listen for messages from Kafka topics. But there are many scenarios where we might need to dynamically start or stop a Kafka listener based on certain conditions. This can be achieved using KafkaListenerEndpointRegistry, which allows programmatic control over the lifecycle of the Kafka Listener.

In this article, we will learn different ways to control Kafka listeners in the Spring Boot application to optimize message processing and resource management.

What is Kafka Listener?

A Kafka Listener is a Spring Bean that listens to a Kafka topic. It processes incoming messages and provides a convenient way to consume Kafka data asynchronously. Kafka Listeners are configured with the @KafkaListener annotation and are started automatically when the application launches.

Different Approaches to Start/Stop a Kafka Listener

There are different ways to control Kafka listeners dynamically:

  1. Controlling Listeners Based on Message Processing
  2. Using @KafkaListener with autoStartup Property
  3. Manual Control with KafkaListenerEndpointRegistry

1. Controlling Listeners Based on Message Processing

This is a common use case for dynamic listener control is to start listeners only when needed to process Kafka messages. After processing, listeners are stopped to save resources. This is useful when handling messages in bursts, as it prevents listeners from running when there are no messages to process.

Example: In this approach, start the listener when a message is detected, and once the message processing is complete, stop the listener.

Java
@Component public class KafkaListenerControl {      @Autowired        // Injecting Kafka listener registry     private KafkaListenerEndpointRegistry registry;       // Start the listener if it is not already running     public void startListener(String listenerId) {                // Get the listener container by ID         MessageListenerContainer container =            registry.getListenerContainer(listenerId);                // Check if container exists and is not running         if (container != null && !container.isRunning()) {                         // Start the listener container             container.start();                        // Log listener start             logger.info("Listener {} started.", listenerId);          }     }      // Stop the listener if it is currently running     public void stopListener(String listenerId) {                // Get the listener container by ID         MessageListenerContainer container =            registry.getListenerContainer(listenerId);                // Check if container exists and is running         if (container != null && container.isRunning()) {                         // Stop the listener container             container.stop();                         // Log listener stop             logger.info("Listener {} stopped.", listenerId);          }     } } 

This approach allows a good control over Kafka listeners and it enable us to start and stop them based on specific conditions or messages being processed.

2. Using @KafkaListener with autoStartup Property

This is one of the simplest ways to control when a Kafka listener starts is to use the autoStartup attribute of the @KafkaListener annotation. By setting autoStartup to false, the listener will not start automatically with the application. It can be started manually based on application logic.

@KafkaListener(id = "dynamicListener", topics = "test-topic", groupId = "test-group", autoStartup = "false")
public void processMessage(Message message) {
logger.info("Processing message: {}", message);
}

In this example, the listener does not start automatically upon application startup. Instead, it can be triggered to start manually using the KafkaListenerEndpointRegistry.

3. Manual Control with KafkaListenerEndpointRegistry

The KafkaListenerEndpointRegistry provides a programmatic interface to start, stop, or manage Kafka listeners manually. This is useful when the listener needs to start or stop based on certain events, such as a user registration or an API call.

@Autowired
KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

To start Kafka Listener:

public boolean startListener(String listenerId) {
MessageListenerContainer listenerContainer = kafkaListenerEndpointRegistry.getListenerContainer(listenerId);
assert listenerContainer != null : "Listener not found!";
listenerContainer.start();
logger.info("{} Kafka Listener Started", listenerId);

To stop Kafka Listener:

public boolean stopListener(String listenerId) {
MessageListenerContainer listenerContainer = kafkaListenerEndpointRegistry.getListenerContainer(listenerId);
assert listenerContainer != null : "Listener not found!";
listenerContainer.stop();
logger.info("{} Kafka Listener Stopped.", listenerId);

We will be implementing the above syntactical approaches as an example below.

Implementing Start/Stop Kafka Listener Dynamically

We will implement a simple example to start or stop a specific Kafka listener.

Note: To know, integration of Apache Kafka with Spring Boot, refer this article: Spring Boot - Integration with Kafka

1. Define a Message Class

Java
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;  @Data @AllArgsConstructor @NoArgsConstructor public class Message {     private String message; } 

2. Configure Kafka Consumer:

Java
@Configuration public class KafkaConsumerConfig {      private String kafkaUrl = "localhost:9092";      @Bean     public ConsumerFactory<String, Message>        messageConsumerFactory() {         JsonDeserializer<Message> deserializer =            new JsonDeserializer<>(Message.class, false);         deserializer.setRemoveTypeHeaders(false);         deserializer.addTrustedPackages("*");          Map<String, Object> config = new HashMap<>();         config.put           (ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUrl);         config.put           (ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);         config.put           (ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);         config.put           (ConsumerConfig.GROUP_ID_CONFIG, "group-1");         return new DefaultKafkaConsumerFactory<>           (config, new StringDeserializer(), deserializer);     }      @Bean     public ConcurrentKafkaListenerContainerFactory<String, Message>        messageListenerFactory() {         ConcurrentKafkaListenerContainerFactory<String, Message>            containerFactory = new ConcurrentKafkaListenerContainerFactory<>();         containerFactory.setConsumerFactory(messageConsumerFactory());         return containerFactory;     } } 

3. Create a Kafka Listener:

Create using below necessary parameters:

  • id: The container's unique identifier for this listener. If none is specified, an auto-generated ID is used.
  • groupId: Override the group.id property for the consumer factory with this value for this listener only.
  • topics: The topics of this listener. The entries can be "topic names," "property placeholder keys," or "expressions." The topic name must be resolved from an expression. This uses group management, and Kafka will assign partitions to group members.
  • containerFactory: The beans name of the KafkaListenerContainerFactory that will be used to create the message listener container that will serve this endpoint.
  • autoStartup: Set to true or false to override the container factory's default setting. By default, the value is set to true, and because of this, it'll start consuming messages as soon as our application starts.
Java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.KafkaListener;  @Configuration public class KafkaMessageListener {      Logger logger = LoggerFactory.getLogger(KafkaMessageListener.class);      @KafkaListener(id = "id-1", groupId = "group-1", topics = "Message-topic",                     containerFactory = "messageListenerFactory", autoStartup = "false")     public void consumeMessage(Message message) {         logger.info("Message received : -> {}", message);     } } 

4. Control Kafka Listener (Start/Stop):

The KafkaListenerEndpointRegistry class can be used to get a Kafka Listener Container by listenerId. Here we have used @KafkaListener annotation to stating the bean method as a listener for the Kafka Listener Container. The Kafka Listener can now be started or stopped using this container.

Java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.config.KafkaListenerEndpointRegistry; import org.springframework.kafka.listener.MessageListenerContainer; import org.springframework.stereotype.Component;  @Component public class KafkaListenerAutomation {      private final Logger logger =        LoggerFactory.getLogger(KafkaListenerAutomation.class);      @Autowired     KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;      public boolean startListener(String listenerId) {         MessageListenerContainer listenerContainer =            kafkaListenerEndpointRegistry.getListenerContainer(listenerId);         assert listenerContainer != null : "Listener not found!";         listenerContainer.start();         logger.info("{} Kafka Listener Started", listenerId);         return true;     }      public boolean stopListener(String listenerId) {         MessageListenerContainer listenerContainer            = kafkaListenerEndpointRegistry.getListenerContainer(listenerId);         assert listenerContainer != null : "Listener not found!";         listenerContainer.stop();         logger.info("{} Kafka Listener Stopped.", listenerId);         return true;     } } 

5. API Endpoints to Control Kafka Listener:

Using API endpoints, we can start or stop a specific Kafka listener by providing the listenerId.

Java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;  @RestController public class StartOrStopListenerController {      @Autowired     KafkaListenerAutomation kafkaListenerAutomation;      @GetMapping("/start")     public void start(@RequestParam("id") String listenerId) {         kafkaListenerAutomation.startListener(listenerId);     }      @GetMapping("/stop")     public void stop(@RequestParam("id") String listenerId) {         kafkaListenerAutomation.stopListener(listenerId);     } } 

Output:

1. Kafka Listener started:

Access the following endpoint to start a listener:

GET /start?id=id-1

When the listener is started, you will see the below log message:

Kafka-Listener-Started


2. Kafka Listener received message:

When the listener processes a message, you should see a log message similar like below:

Message received: -> {message: "Your Message Content"}

3. Kafka Listener stopped:

Access the below endpoint to stop the listener:

GET /stop?id=id-1

When the listener is stopped, you will see the below log message:

Kafka-Listener-Stopped

Note: To know more how to run Apache Kafka, refer this article: How to Install and Run Apache Kafka on Windows?

Conclusion

In this article, we learned how to dynamically start and stop Kafka listeners in a Spring Boot application. Using KafkaListenerEndpointRegistry gives us programmatic control over the listener lifecycle. We also explored the autoStartup property of @KafkaListener for simpler control. This allows us to optimize Kafka message processing based on conditions.


Next Article
Spring Boot - Start/Stop a Kafka Listener Dynamically

M

malavmevada
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Advance Java
  • Technical Scripter 2022
  • Java-Spring
  • Java-Spring-Boot
  • Apache Kafka Java
Practice Tags :
  • Java

Similar Reads

    Best Way to Master Spring Boot – A Complete Roadmap
    In the corporate world, they say "Java is immortal!". But Why? Java remains one of the major platforms for developing enterprise applications. Enterprise Applications are used by large companies to make money. Those applications have high-reliability requirements and an enormous codebase. According
    14 min read
    How to Create a Spring Boot Project?
    Spring Boot is built on top of the spring and contains all the features of spring. It is one of the most popular frameworks for building Java-based web applications and microservices. It is a favorite among developers due to its rapid, production-ready environment, which allows developers to focus o
    6 min read
    Spring Boot - Annotations
    Spring Boot Annotations are a form of metadata that provides data about a spring application. 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
    7 min read
    Spring Boot - Architecture
    Spring Boot is built on top of the core Spring framework. It simplifies and automates Spring-based application development by reducing the need for manual configuration. Spring Boot follows a layered architecture, where each layer interacts with other layers in a hierarchical order. The official Spr
    3 min read
    Spring Boot Actuator
    Developing and managing an application are the two most important aspects of the application’s life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
    5 min read
    Spring Boot - Introduction to RESTful Web Services
    RESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
    5 min read
    How to create a basic application in Java Spring Boot
    Spring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
    3 min read
    How to Create a REST API using Java Spring Boot?
    Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
    4 min read
    Easiest Way to Create REST API using Spring Boot
    Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
    10 min read
    Java Spring Boot Microservices Sample Project
    Microservices are more popular nowadays. They can be written in any language. In this article, let us see Spring Boot Microservices. in this article let us see a base project "currency-exchange-sample-service" which has a business logic and which can be invoked in another project "currency-conversio
    9 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