Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a Kafka consumer with the correct group ID.
Kafka
Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "[1]"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an empty string as group ID
Using an invalid property key
✗ Incorrect
The group ID identifies the consumer group. Here, 'consumer1' is used as the group ID.
2fill in blank
mediumComplete the code to subscribe the consumer to a topic named 'test-topic'.
Kafka
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); consumer.[1](Collections.singletonList("test-topic"));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using assign() instead of subscribe()
Using a non-existent method like listen()
✗ Incorrect
The subscribe() method is used to subscribe the consumer to one or more topics.
3fill in blank
hardFix the error in the code to correctly poll messages from Kafka.
Kafka
ConsumerRecords<String, String> records = consumer.[1](100);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using fetch() or read() instead of poll()
Passing wrong argument types to poll()
✗ Incorrect
The poll() method is used to fetch records from Kafka. The argument should be a Duration in newer versions, but here an integer is used for simplicity.
4fill in blank
hardFill both blanks to process each record and print its key and value.
Kafka
for (ConsumerRecord<String, String> record : records) { System.out.println("Key: " + record.[1]() + ", Value: " + record.[2]()); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using key() or value() methods which do not exist
Trying to access key or value as public fields
✗ Incorrect
The ConsumerRecord class provides getKey() and getValue() methods to access the key and value.
5fill in blank
hardFill all three blanks to commit offsets synchronously after processing records.
Kafka
try { consumer.[1](); } catch ([2] e) { e.[3](); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using commitAsync() instead of commitSync()
Catching wrong exception types
Not printing the stack trace in catch block
✗ Incorrect
commitSync() commits offsets synchronously. InterruptedException is caught and printStackTrace() prints the error.