123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import org.apache.kafka.clients.consumer.ConsumerConfig;
- import org.apache.kafka.clients.consumer.ConsumerRecord;
- import org.apache.kafka.clients.consumer.ConsumerRecords;
- import org.apache.kafka.clients.consumer.KafkaConsumer;
- import org.apache.kafka.common.TopicPartition;
- import org.apache.kafka.common.serialization.StringDeserializer;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Properties;
- public class KafkaAssignApp {
- public static final String TOPIC = "my-topic";
- public static final Integer TIMEOUT = 10;
- public static void main(String[] args) {
- Properties props = new Properties();
- // We use "put" since there are strings. Otherwise, use setProperty.
- props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
- props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
- props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
- // props.put(ConsumerConfig.GROUP_ID_CONFIG, "demo");
- KafkaConsumer<String, String> myConsumer = new KafkaConsumer<String, String>(props);
- ArrayList<TopicPartition> partitions = new ArrayList<TopicPartition>();
- TopicPartition myTopicPart0 = new TopicPartition(TOPIC, 0);
- TopicPartition myTopicPart1 = new TopicPartition(TOPIC, 1);
- partitions.add(myTopicPart0);
- // Will block poll if the partition does not exist.
- partitions.add(myTopicPart1);
- myConsumer.assign(partitions);
- Boolean started = false;
- Integer pass = 0;
- try {
- while (true) {
- ConsumerRecords<String, String> records = myConsumer.poll(TIMEOUT);
- if (!started) {
- started = true;
- System.out.printf("Started");
- }
- for (ConsumerRecord<String, String> cr : records) {
- System.out.printf("Pass: %d/%d Topic: %s Partition: %d, Offset: %d, Key: %s Value: %s\n",
- pass, records.count(),
- cr.key(), cr.partition(), cr.offset(), cr.key(), cr.value());
- }
- pass++;
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- myConsumer.close();
- }
- }
- }
|