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 myConsumer = new KafkaConsumer(props); ArrayList partitions = new ArrayList(); 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 records = myConsumer.poll(TIMEOUT); if (!started) { started = true; System.out.printf("Started"); } for (ConsumerRecord 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(); } } }