Java consumer client in Kafka - Commands & Configuration
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public class ConsumerExample {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "example-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("example-topic"));
try {
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.printf("Received message: key = %s, value = %s, offset = %d\n", record.key(), record.value(), record.offset());
}
}
} finally {
consumer.close();
}
}
}
This Java file creates a Kafka consumer client.
Properties: Set Kafka server address, consumer group, and deserializers for keys and values.
KafkaConsumer: Creates the consumer with these properties.
subscribe: Tells the consumer which topic to listen to.
poll: Checks for new messages every 100 milliseconds.
Processing loop: Prints each message's key, value, and offset.
close: Cleans up resources when done.
javac -cp kafka-clients-3.5.1.jar ConsumerExample.java
java -cp .:kafka-clients-3.5.1.jar ConsumerExample
If you remember nothing else from this pattern, remember: the consumer must subscribe to topics and poll regularly to receive messages.
Practice
What is the main purpose of a Java consumer client in Kafka?
Solution
Step 1: Understand Kafka client roles
Kafka clients include producers (send messages) and consumers (read messages).Step 2: Identify the consumer's role
The Java consumer client reads messages from Kafka topics to process or display them.Final Answer:
To read messages from Kafka topics -> Option CQuick Check:
Consumer = reads messages [OK]
- Confusing consumer with producer
- Thinking consumer creates topics
- Assuming consumer deletes topics
Which of the following is the correct way to subscribe a Kafka consumer to a topic named my-topic?
consumer._____ (Collections.singletonList("my-topic"));Solution
Step 1: Understand consumer methods
Thesubscribemethod registers the consumer to listen to topics.Step 2: Match method to code
Usingconsumer.subscribe(Collections.singletonList("my-topic"))correctly subscribes to the topic.Final Answer:
subscribe -> Option AQuick Check:
Subscribe = listen to topics [OK]
- Using assign() instead of subscribe()
- Calling poll() to subscribe
- Using commitSync() incorrectly
What will the following Java Kafka consumer code print if the topic has one message with value "Hello Kafka"?
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.println(record.value());
}Solution
Step 1: Poll messages from topic
Thepollmethod fetches available messages; here it gets one message.Step 2: Print each message value
The loop prints thevalue()of each record, which is "Hello Kafka".Final Answer:
Hello Kafka -> Option AQuick Check:
Print record.value() = Hello Kafka [OK]
- Printing the record object instead of value
- Expecting poll() to return null if no messages
- Confusing key and value fields
Identify the error in this Kafka consumer code snippet:
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "group1");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("my-topic"));
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.println(record.value());
}Solution
Step 1: Check poll() method signature
In modern Kafka clients,pollrequires aDurationargument, not an int.Step 2: Identify incorrect argument type
The code usespoll(100)(int), should bepoll(Duration.ofMillis(100)).Final Answer:
poll() argument should be Duration, not int -> Option DQuick Check:
poll() needs Duration argument [OK]
- Passing int to poll() instead of Duration
- Missing group.id property
- Using assign() instead of subscribe()
You want to consume messages from two topics topicA and topicB and print their keys and values. Which code snippet correctly subscribes and processes messages?
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "group1");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer._____ (Arrays.asList("topicA", "topicB"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.println("Key: " + record.key() + ", Value: " + record.value());
}
}Solution
Step 1: Choose method to listen to multiple topics
subscribeaccepts a list of topics to listen to, whileassignassigns specific partitions.Step 2: Confirm correct usage in code
Usingconsumer.subscribe(Arrays.asList("topicA", "topicB"))subscribes to both topics properly.Final Answer:
subscribe -> Option BQuick Check:
subscribe() listens to multiple topics [OK]
- Using assign() instead of subscribe() for topics
- Calling poll() to subscribe
- Forgetting to print keys
Ready to prove it?
Pass the test and this pattern moves unknown
