在 Linux 上消费 Kafka 消息,常见方式有以下几种(从最常用到编程方式):
Kafka 安装包里自带 kafka-console-consumer.sh。
bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic
bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--from-beginning
bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--group my-group
bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--property print.key=true
bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group my-group
适合不熟悉命令行的场景:
pip install kafka-python
from kafka import KafkaConsumer
consumer = KafkaConsumer(
'test-topic',
bootstrap_servers='localhost:9092',
auto_offset_reset='earliest',
group_id='my-group'
)
for msg in consumer:
print(msg.value.decode())
KafkaConsumer<String, String> consumer =
new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test-topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> r : records) {
System.out.println(r.value());
}
}
--from-beginningtelnet localhost 9092
确认 Kafka 正在运行
如果你能告诉我:
我可以给你更精确的示例。