在 Linux 环境下消费 Kafka 消息,常见方式有以下几种,从最常用命令行到编程方式都给你说明。
localhost:9092)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=":"
适合:
pip install kafka-python
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())
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
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) {
consumer.poll(Duration.ofMillis(100))
.forEach(record -> System.out.println(record.value()));
}
--from-beginningtelnet localhost 9092
kafka-topics.sh --bootstrap-server localhost:9092 --list
如果你愿意,可以告诉我:
我可以给你更精准的命令或示例。