java获取kafka偏移量
时间: 2023-07-03 19:29:22 浏览: 164
java操作kafka
要获取Kafka偏移量,可以使用Kafka Consumer API提供的方法。以下是获取Kafka偏移量的示例代码:
```java
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 KafkaOffsetExample {
private static final String TOPIC_NAME = "my-topic";
private static final String BOOTSTRAP_SERVERS = "localhost:9092";
private static final String GROUP_ID = "my-group";
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
props.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
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);
// 订阅主题
consumer.subscribe(Arrays.asList(TOPIC_NAME));
// 获取分区
TopicPartition partition = new TopicPartition(TOPIC_NAME, 0);
// 获取偏移量
long offset = consumer.position(partition);
System.out.println("Offset: " + offset);
// 关闭消费者
consumer.close();
}
}
```
在这个例子中,我们使用KafkaConsumer类获取Kafka偏移量。首先,我们创建KafkaConsumer实例并订阅主题。然后,我们获取分区并使用position()方法获取当前偏移量。最后,我们打印偏移量并关闭消费者。
阅读全文