0


获取kafka中topic偏移量和消费偏移量

1、kafkaclient版本1.0.1

public class MutiThreadScheduleTask {

@Resource
private KafkaConsumer<String, String> kafkaConsumer;

public void test(String topic) {
        
            //查询 topic partitions
            List<TopicPartition> topicPartitionList = new ArrayList<>();

            List<PartitionInfo> partitionInfoList = kafkaConsumer.partitionsFor(topic);
            for (PartitionInfo partitionInfo : partitionInfoList) {
                TopicPartition topicPartition = new TopicPartition(partitionInfo.topic(), partitionInfo.partition());
                topicPartitionList.add(topicPartition);
            }

            //查询总偏移量
            Map<Integer, Long> endOffsetMap = new HashMap<>();
            Map<TopicPartition, Long> endOffsets = kafkaConsumer.endOffsets(topicPartitionList);
            for (TopicPartition partitionInfo : endOffsets.keySet()) {
                endOffsetMap.put(partitionInfo.partition(), endOffsets.get(partitionInfo));
            }

            //查询消费消费偏移量
            Map<Integer, Long> commitOffsetMap = new HashMap<>();
            for (TopicPartition topicAndPartition : topicPartitionList) {
                OffsetAndMetadata committed = kafkaConsumer.committed(topicAndPartition);
                commitOffsetMap.put(topicAndPartition.partition(), committed.offset());
            }
            
    }
}

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

标签: java kafka

本文转载自: https://blog.csdn.net/qq_40155654/article/details/136913571
版权归原作者 小一猿 所有, 如有侵权,请联系我们删除。

“获取kafka中topic偏移量和消费偏移量”的评论:

还没有评论