Kafka 消费者组代码
时间: 2023-07-09 21:14:30 浏览: 120
以下是使用Java语言编写的Kafka消费者组代码示例:
```java
import java.util.Properties;
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;
public class KafkaConsumerGroupExample {
private final static String TOPIC_NAME = "test_topic";
private final static String GROUP_ID = "test_group";
private final static String BOOTSTRAP_SERVERS = "localhost:9092,localhost:9093,localhost:9094";
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, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(1000);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
}
}
```
在这个示例中,我们创建了一个Kafka消费者对象,并向其传递了一些配置参数,包括bootstrap.servers、group.id、key.deserializer和value.deserializer等参数。然后,我们将消费者订阅了一个主题(test_topic),并在一个无限循环中不断地拉取消息并进行处理。在处理消息的过程中,我们可以使用ConsumerRecord对象获取消息的偏移量(offset)、键(key)和值(value)等信息。
阅读全文