如何在特定偏移量到特定偏移量中使用来自 kafka 主题的数据?

iti*_*pa1 5 java apache-kafka kafka-consumer-api

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

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

Mic*_*son 9

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

例如,要从偏移量 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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • spring Kafka 有什么方法吗?我尝试了运气,但无法在春季卡夫卡中做同样的事情 (2认同)