[英]how to get kafka lag using java
我目前开发了一个代码来显示主题、分区和日志偏移量。 但我目前被困在如何获得分区的滞后上。 我知道有一个 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();
我需要做的是输出主题,分区,当前偏移量,日志偏移量和滞后。 如何获得代码的滞后或如何获得代码的当前偏移量。 (有关所需的输出,请参见图像)。
注意:我不能使用 (foreach record) 功能,因为我不能读取输入文件中的每条记录。
要重现kafka-consumer-groups
功能,您需要一个 Consumer 和一个 AdminClient 实例。
首先,使用 AdminClient,您可以调用listConsumerGroupOffsets()
来检索特定组的主题分区列表和已提交的偏移量。
然后使用消费者获取这些分区的结束偏移量。 您使用的方法效率低下,无需分配和查找结束偏移量。 您可以简单地调用endOffsets()
。
这足以重现屏幕截图中包含的数据。
kafka-consumer-groups
还使用AdminClient.describeConsumerGroups()
打印分配给每个分区的组成员(如果有)。
您可以通过从消费者那里获取 EndOffset 来获得 LAG
Set<TopicPartition> partitionSet = consumer.assignment();
Map<TopicPartition, Long> endOffsets =consumer.endOffsets(consumer.assignment());
然后迭代哪里过集
for(TopicPartition tp : partitionSet) { LOG.info("Topic :: {} ,EndOffset :: {}, currentOffset {}",tp.topic(),beginningOffsets.get(tp),endOffsets.get(tp), consumer.position(tp)); }
consumer.position(tp) -- 会得到你当前的偏移量,从 endoffset 中减去它,你得到 LAG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.