在 Linux 下消费 Kafka 数据,常见有 命令行方式 和 编程方式。下面按使用频率给你讲清楚。
localhost:9092)test_topic)kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test_topic
只消费启动之后新产生的消息
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test_topic \
--from-beginning
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test_topic \
--group my_group \
--from-beginning
查看消费进度:
kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group my_group
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test_topic \
--property print.key=true \
--property key.separator=":"
| 参数 | 说明 |
|---|---|
--bootstrap-server |
Kafka 集群地址 |
--topic |
消费的 topic |
--group |
消费者组 |
--from-beginning |
从头消费 |
--max-messages |
消费多少条后退出 |
--partition |
指定分区 |
示例:
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test_topic \
--partition 0 \
--offset 10
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(List.of("test_topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> r : records) {
System.out.println(r.key() + " : " + r.value());
}
}
from kafka import KafkaConsumer
consumer = KafkaConsumer(
'test_topic',
bootstrap_servers='localhost:9092',
group_id='my_group',
auto_offset_reset='earliest'
)
for msg in consumer:
print(msg.value.decode())
kafka-topics.sh --list如果你愿意,可以告诉我:
我可以给你更精确的命令或示例。