[英]How to consume messages from Kafka in Java, starting from a specific offset
从最早的阅读:
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
从最新阅读:
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
但是如果我想开始,我应该使用哪一行:从第 18 次提交开始?
您可以使用seek()
来强制消费者从特定偏移量开始消费:
public void seek(TopicPartition partition, long offset)
覆盖消费者将在下一次
poll(timeout)
上使用的获取偏移量。 如果多次为同一个分区调用此 API,则将在下一次poll()
中使用最新的偏移量。 请注意,如果在消费过程中任意使用此 API 来重置获取偏移量,您可能会丢失数据
例如,假设您要从偏移量18
开始:
TopicPartition topicPartition = new TopicPartition("myTopic", 0);
Long startOffset = 18L;
List<TopicPartition> topics = Arrays.asList(topicPartition);
consumer.assign(topics);
consumer.seek(topicPartition, startOffset);
// Then consume messages as normal..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.