当前位置:   article > 正文

获取kafka中topic偏移量和消费偏移量_kafka查询topic的offset

kafka查询topic的offset

 1、kafkaclient版本1.0.1

  1. public class MutiThreadScheduleTask {
  2. @Resource
  3. private KafkaConsumer<String, String> kafkaConsumer;
  4. public void test(String topic) {
  5. //查询 topic partitions
  6. List<TopicPartition> topicPartitionList = new ArrayList<>();
  7. List<PartitionInfo> partitionInfoList = kafkaConsumer.partitionsFor(topic);
  8. for (PartitionInfo partitionInfo : partitionInfoList) {
  9. TopicPartition topicPartition = new TopicPartition(partitionInfo.topic(), partitionInfo.partition());
  10. topicPartitionList.add(topicPartition);
  11. }
  12. //查询总偏移量
  13. Map<Integer, Long> endOffsetMap = new HashMap<>();
  14. Map<TopicPartition, Long> endOffsets = kafkaConsumer.endOffsets(topicPartitionList);
  15. for (TopicPartition partitionInfo : endOffsets.keySet()) {
  16. endOffsetMap.put(partitionInfo.partition(), endOffsets.get(partitionInfo));
  17. }
  18. //查询消费消费偏移量
  19. Map<Integer, Long> commitOffsetMap = new HashMap<>();
  20. for (TopicPartition topicAndPartition : topicPartitionList) {
  21. OffsetAndMetadata committed = kafkaConsumer.committed(topicAndPartition);
  22. commitOffsetMap.put(topicAndPartition.partition(), committed.offset());
  23. }
  24. }
  25. }

2、这部分测试代码和真正的消费端不在一个程序内,连接kafka时随便配置了一个groupId,然后kafkaConsumer.committed(topicAndPartition)一直为null。后来groupId改成和消费者一致时能成功查到。如果测试代码有个消费程序在消费其他topic,则上面代码中的KafkaConsumer要单独生成一个对象,单独指定这个groupId。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/812438
推荐阅读
相关标签
  

闽ICP备14008679号