如何使用java获得kafka滞后

Ard*_*iel 2 java apache-kafka kafka-consumer-api

我目前开发了一个代码来显示主题、分区和日志偏移量。但我目前被困在如何获得分区的滞后上。我知道有一个 kafka offset 命令可以完成这个功能,但我需要的是一个 java 代码。

public static void main(String[] args) throws Exception {
    System.out.println("START CONSUMER");final Properties props = new Properties();
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, GROUPID);
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

    // Create the consumer using props.
    final Consumer<Long, String> consumer =  new KafkaConsumer<>(props);

    // Subscribe to the topic.
    int i = 0;
    ArrayList<TopicPartition> partitions = new ArrayList<TopicPartition>();
    for (i=0;i<consumer.partitionsFor(TOPIC).size();i++)
    {
        TopicPartition partitiontemp = new TopicPartition(TOPIC, i);
        partitions.add(partitiontemp);
    }
    consumer.assign(partitions);
    consumer.seekToEnd(partitions);

    for (i=0;i<consumer.partitionsFor(TOPIC).size();i++)
    {
        System.out.printf("Topic: %s partitionID: %d log offset: %d \n", TOPIC, i, consumer.position(partitions.get(i)));
    }

    System.out.printf("CREATE CONSUMER DONE");
    consumer.close();
Run Code Online (Sandbox Code Playgroud)

这是我的代码的输出

我需要做的是输出主题,分区,当前偏移量,日志偏移量和滞后。如何获得代码的滞后或如何获得代码的当前偏移量。(有关所需的输出,请参见图像)。

需要的输出

注意:我不能使用 (foreach record) 功能,因为我不能读取输入文件中的每条记录。

Mic*_*son 6

要重现该kafka-consumer-groups功能,您需要一个 Consumer 和一个 AdminClient 实例。

首先,使用 AdminClient,您可以调用listConsumerGroupOffsets()以检索特定组的主题分区列表和已提交的偏移量。

然后使用消费者获取这些分区的结束偏移量。您使用的方法效率低下,无需分配和查找结束偏移量。您可以简单地调用endOffsets().

这足以重现屏幕截图中包含的数据。

kafka-consumer-groups还用于AdminClient.describeConsumerGroups()打印分配给每个分区的组成员(如果有)。