kafka消费者代码实现key
时间: 2023-11-11 07:05:30 浏览: 118
Kafka消费者代码实现key的过程如下:
1. 创建KafkaConsumer对象,指定key和value的反序列化器。
2. 调用subscribe()方法订阅主题。
3. 调用poll()方法获取消息记录,返回的是ConsumerRecords对象。
4. 遍历ConsumerRecords对象,获取每个消息记录的key和value。
以下是一个简单的Kafka消费者代码实现key的示例:
```
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.serialization.StringDeserializer;
import java.util.Collections;
import java.util.Properties;
public class KafkaConsumerExample {
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.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test-topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(1000);
for (ConsumerRecord<String, String> record : records) {
String key = record.key();
String value = record.value();
System.out.println("key: " + key + ", value: " + value);
}
}
}
}
```
阅读全文