-
-
Save vndung/4c9527b3aeafec5d3245c7a3b921f8b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vnd.basics; | |
import org.apache.kafka.clients.consumer.ConsumerConfig; | |
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; | |
import org.apache.kafka.clients.consumer.KafkaConsumer; | |
import org.apache.kafka.common.TopicPartition; | |
import org.apache.kafka.common.serialization.StringDeserializer; | |
import java.time.Duration; | |
import java.util.Collection; | |
import java.util.Map; | |
import java.util.Set; | |
import static java.lang.System.out; | |
public class Consumer { | |
public static void main(String[] args) { | |
var topic = "basic"; | |
Map<String, Object> config = | |
Map.of(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092", | |
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName(), | |
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName(), | |
ConsumerConfig.GROUP_ID_CONFIG, "basic-consumer", | |
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest", | |
ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); | |
try (var consumer = new KafkaConsumer<String, String>(config)) { | |
consumer.subscribe(Set.of(topic), new ConsumerRebalanceListener() { | |
@Override | |
public void onPartitionsRevoked(Collection<TopicPartition> partitions) { | |
} | |
@Override | |
public void onPartitionsAssigned(Collection<TopicPartition> partitions) { | |
consumer.seekToBeginning(partitions); | |
} | |
}); | |
while (true) { | |
var records = consumer.poll(Duration.ofMillis(100)); | |
for (var record : records) { | |
out.format("Got record with value %s%n", record.value()); | |
} | |
consumer.commitAsync(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment