kafka 消费者确认 代码
时间: 2023-06-28 19:07:20 浏览: 107
kafka生产者消费者helloword代码
下面是使用 Java 语言编写的 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.Collections;
import java.util.Properties;
public class ConsumerWithManualCommit {
public static void main(String[] args) {
// 配置消费者属性
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // 禁止自动提交位移
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(Collections.singletonList("test-topic"));
try {
while (true) {
ConsumerRecords<String, String> records = consumer.poll(1000);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("topic = %s, partition = %d, offset = %d, key = %s, value = %s\n",
record.topic(), record.partition(), record.offset(), record.key(), record.value());
// 手动确认消息已经被消费
TopicPartition tp = new TopicPartition(record.topic(), record.partition());
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(record.offset() + 1)));
}
}
} finally {
consumer.close();
}
}
}
```
在上述代码中,设置了 `ENABLE_AUTO_COMMIT_CONFIG` 属性为 false,禁止自动提交位移。在消费消息的循环中,手动确认消息已经被消费,然后再提交位移。这样可以保证消息不会被重复消费,同时也可以避免消息丢失。
阅读全文