阅读量:0
可以使用seek()
方法来指定offset进行读取。
示例代码如下:
import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.TopicPartition; import java.util.Arrays; import java.util.Properties; public class KafkaOffsetReader { public static void main(String[] args) { String topicName = "my_topic"; int partition = 0; long offset = 100; // 设置Kafka consumer的配置 Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "my_consumer_group"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); // 创建TopicPartition对象来指定要读取的partition和offset TopicPartition topicPartition = new TopicPartition(topicName, partition); // 使用seek()方法来指定offset consumer.assign(Arrays.asList(topicPartition)); consumer.seek(topicPartition, offset); // 开始消费消息 while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { System.out.println("Received message: " + record.value()); } } } }
在上述示例中,我们创建了一个Kafka consumer,并使用seek()
方法将consumer的offset设置为指定的值。然后,我们使用poll()
方法来获取消息,从指定的offset开始消费。