可以使用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開始消費。