使用偏移量回到卡夫卡

时间:2016-12-14 09:04:03

标签: java apache-kafka

是否有办法使用我们传递的初始属性

从特定偏移量启动使用者

我知道有props.put(" auto.offset.reset","最早")但这让我开始。

但是我想回去,我的情景如下

  1. 指定我想从
  2. 开始的偏移量
  3. 指定我要开始的时间
  4. 我希望使用初始属性作为首选选项。 如果那是不可能的,那么使用其他机制

    附上我的简单消费者代码以供参考

    import java.util.Arrays;
    import java.util.Properties;
    import org.apache.kafka.clients.consumer.ConsumerRecord;
    import org.apache.kafka.clients.consumer.ConsumerRecords;
    import org.apache.kafka.clients.consumer.KafkaConsumer;
    
    public class SimpleConsumer {
    
        public static void main(String[] args) throws Exception {
    
            String topicName = "test3";
            Properties props = new Properties();
    
            String groupId = "single";
    
            // Kafka consumer configuration settings
            props.put("bootstrap.servers", "mymachine:9092");
            props.put("group.id", groupId);
            props.put("enable.auto.commit", "true");
            props.put("auto.commit.interval.ms", "1000");
            props.put("session.timeout.ms", "30000");
            props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
            props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
            props.put("auto.offset.reset", "earliest");
    
            KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
            consumer.subscribe(Arrays.asList(topicName));
    
            System.out.println("Starting the _NON-BATCH_ consumer ::: Topic=" + topicName+" GroupId="+groupId);
    
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(100);
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("%s   (offset:%d, key:%s, partition = %s, topic = %s)", record.value(), record.offset(), record.key(), record.partition(), record.topic());
                    System.out.println();
                }
            }
        }
    }
    

1 个答案:

答案 0 :(得分:2)

对于方案1,您可以使用KafkaConsumer.seek(TopicPartition,offset)来指定您从中读取的偏移量。

对于场景2,Kafka 0.10.1.0提供了KafkaConsumer.offsetsForTimes方法,允许您通过时间戳查找给定分区的偏移量,然后调用seek()方法来检索所需的所需消息。