[英]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.