如何使用Kafka主题中特定偏移量到特定偏移量的数据?

时间:2019-06-02 08:39:40

标签: java apache-kafka kafka-consumer-api

我需要消耗特定的偏移量到特定的结束偏移量!! Consumer.seek()从特定的偏移量读取数据,但是我需要从offset到tooffset检索数据!任何帮助将不胜感激,在此先感谢。

    ConsumerRecords<String, String> records = consumer.poll(100);
    if(flag) {
        consumer.seek(new TopicPartition("topic-1", 0), 90);
        flag = false;
    }

1 个答案:

答案 0 :(得分:4)

要从开始偏移量到结束偏移量读取消息,首先需要使用seek()将使用者移动到所需的起始位置,然后使用poll()直到达到所需的末端偏移量。 / p>

例如,要从偏移量100消耗到200:

String topic = "test";
TopicPartition tp = new TopicPartition(topic, 0);

try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configs);) {
    consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener() {
        @Override
        public void onPartitionsRevoked(Collection<TopicPartition> partitions) {}

        @Override
        public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
            // Move to the desired start offset 
            consumer.seek(tp, 100L);
        }
    });
    boolean run = true;
    long lastOffset = 200L;
    while (run) {
        ConsumerRecords<String, String> crs = consumer.poll(Duration.ofMillis(100L));
        for (ConsumerRecord<String, String> record : crs) {
            System.out.println(record);
            if (record.offset() == lastOffset) {
                // Reached the end offsey, stop consuming
                run = false;
                break;
            }
        }
    }
}