Kafka获取Topic中两端的偏移

监控Topic的情况时需要查看Topic队列的收尾的偏移情况, API中没有提供直接的方法, 不过可以按以下方法间接获取

思路

在Java中查看consumer在Topic的偏移情况可以用consumer.position(topicPartition), 所以可以创建一个consumer, 通过seekToBeginning()seekToEnd()把偏移定位到首尾后再获取当前偏移

例子

1
2
3
4
5
6
7
private void printOffset(KafkaConsumer consumer, TopicPartition topicPartition){
List<TopicPartition> topicPartitions = Collections.singletonList(topicPartition);
consumer.seekToBeginning(topicPartitions);
System.out.println("BeginningOffset: " + consumer.position(topicPartition));
consumer.seekToEnd(topicPartitions);
System.out.println("EndOffset: " + consumer.position(topicPartition));
}