Kafka单一使用者可以从具有给定偏移量的多个分区的主题中进行阅读

时间:2019-06-20 16:38:05

标签: apache-kafka kafka-consumer-api

我有一个带有2个分区的kafka主题,我想创建一个使用者以从给定的偏移量读取主题,以下是我用来从给定的偏移量9中读取的示例代码。

Properties configProperties = new Properties();
configProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
configProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
configProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
configProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "test_consumer_group");
configProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");

KafkaConsumer kafkaConsumer = new KafkaConsumer<String, String>(configProperties);
kafkaConsumer.subscribe(Arrays.asList(topicName), new ConsumerRebalanceListener() {
    public void onPartitionsRevoked(Collection<TopicPartition> partitions) {

    }
    public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
        for(TopicPartition topicPartition: partitions) {
            consumer.seek(topicPartition, 9);
        }
    }
});

try {
    while (true) {
        ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
        for (ConsumerRecord<String, String> record : records) {
            System.out.println(record.topic() + ", " + record.partition() + ", " + record.offset() + ", " + record.value());
        }
    }
}catch(WakeupException ex){
    System.out.println("Exception caught " + ex.getMessage());
}finally{
    kafkaConsumer.close();
}

但是我看到以下错误

org.apache.kafka.clients.consumer.internals.Fetcher -  Fetch offset 9 is out of range for parition test-topic_partitions-0, resetting offset
org.apache.kafka.clients.consumer.internals.Fetcher -  Resetting offset for partition test-topic_partitions-0 to offset 

我正在使用以下Maven依赖项

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>2.1.0</version>
</dependency>

还要提一下,为此主题配置的delete.retention.ms为86400000(即1天),而retention.ms被配置为172800000(即2天)

有人可以帮助解决该错误吗?

1 个答案:

答案 0 :(得分:1)

此错误意味着分区在偏移9处没有记录。 所以:

  • 您当前在分区中的记录少于9条
  • 至少9条记录已被保留策略删除

您可以使用endOffsets()beginningOffsets()查找分区中最小和最大的偏移量。如果您尝试寻找超出此范围的偏移量,则重置策略auto.offset.reset会触发以查找有效的偏移量。