【问题标题】:How to consume data from kafka topic in specific offset to specific offset?如何将特定偏移量中来自kafka主题的数据消耗到特定偏移量?
【发布时间】:2020-08-25 16:52:59
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    要从起始偏移量读取消息到结束偏移量,您首先需要使用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;
                }
            }
        }
    }
    

    【讨论】:

    • 春天卡夫卡有什么方法吗!我尝试了运气,但在春季卡夫卡中无法做同样的事情
    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2021-02-22
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多