Java, How to get number of messages in a topic in apache kafka

后端 未结 17 1496
不思量自难忘°
不思量自难忘° 2020-11-30 19:11

I am using apache kafka for messaging. I have implemented the producer and consumer in Java. How can we get the number of messages in a topic?

17条回答
  •  醉酒成梦
    2020-11-30 19:39

    Using the Java client of Kafka 2.11-1.0.0, you can do the following thing :

        KafkaConsumer consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Collections.singletonList("test"));
        while(true) {
            ConsumerRecords records = consumer.poll(100);
            for (ConsumerRecord record : records) {
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
    
                // after each message, query the number of messages of the topic
                Set partitions = consumer.assignment();
                Map offsets = consumer.endOffsets(partitions);
                for(TopicPartition partition : offsets.keySet()) {
                    System.out.printf("partition %s is at %d\n", partition.topic(), offsets.get(partition));
                }
            }
        }
    

    Output is something like this :

    offset = 10, key = null, value = un
    partition test is at 13
    offset = 11, key = null, value = deux
    partition test is at 13
    offset = 12, key = null, value = trois
    partition test is at 13
    

提交回复
热议问题