在 Linux 环境下消费 Kafka 消息,通常有以下几种常见方式。下面从最常用命令行方式到编程方式逐步说明。
Kafka 安装包中自带消费脚本,适合快速验证和调试。
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--from-beginning
说明:
--bootstrap-server:Kafka broker 地址--topic:要消费的主题--from-beginning:从最早消息开始消费(不加重试只消费新消息)kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--group test-group
查看消费者组状态:
kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group test-group
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--partition 0 \
--offset 10
如果你使用的是老版本(< 2.0):
kafka-console-consumer.sh \
--zookeeper localhost:2181 \
--topic test-topic \
--from-beginning
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(Collections.singletonList("test-topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
System.out.println(record.value());
}
}
pip install kafka-python
from kafka import KafkaConsumer
consumer = KafkaConsumer(
'test-topic',
bootstrap_servers='localhost:9092',
group_id='test-group',
auto_offset_reset='earliest'
)
for msg in consumer:
print(msg.value.decode())
kafka-topics.sh --bootstrap-server localhost:9092 --list
--from-beginning 或 auto_offset_resetkafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--group test-group \
--reset-offsets --to-earliest --execute
如果你能告诉我:
我可以给你更精准的命令或示例。