When a Spring Boot application starts, Kafka Listener's default behavior is to begin listening for a certain topic. However, there are situations when we don't want to start it right away once our application launches.
To start or stop a Kafka Listener dynamically we need major three approaches i.e. start/stop when Kafka messages need to be processed, use of @KafkaListener annotation, use of kafkaListenerEndpointRegistry
In this article, we will go through how to dynamically start or stop a Kafka listener.
Different Approaches to Start/Stop a Kafka Listener
Approach 1:
- Start an application, when there is a need for the Kafka messages to be processed.
- Stop an application after successful processing.
Approach 2: While registering Kafka Listener we can set the below id property.
@KafkaListener(id = "id-1", groupId = "group-1", topics = "Message-topic",
containerFactory = "messageListenerFactory", autoStartup = "false")
public void consumeMessage(Message message)
Approach 3: Autowire KafkaListenerEndpointRegistry bean for controlling the start or stop of the Kafka Listener.
@Autowired
KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
To start:
public boolean startListener(String listenerId) {
MessageListenerContainer listenerContainer =
kafkaListenerEndpointRegistry.getListenerContainer(listenerId);
assert listenerContainer != null : false;
listenerContainer.start();
To stop:
public boolean stopListener(String listenerId) {
MessageListenerContainer listenerContainer =
kafkaListenerEndpointRegistry.getListenerContainer(listenerId);
assert listenerContainer != null : false;
listenerContainer.stop();
logger.info("{} Kafka Listener Stopped.", listenerId);
We will be implementing the above syntactical approaches as an example below.
Implementation of start or stop a specific Kafka Listener
Make a class whose objects will be consumed by the Kafka listener.
File: Message.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
private String message;
}