在 CentOS 上设置 Kafka 消费者,通常分为 命令行方式 和 代码方式(Java/Python 等)。下面给你一个从基础到常用的完整说明。
/opt/kafka)localhost:9092)test-topic)启动 Kafka(示例):
# 启动 Zookeeper(老版本)
/opt/kafka/bin/zookeeper-server-start.sh /opt/kafka/config/zookeeper.properties
# 启动 Kafka
/opt/kafka/bin/kafka-server-start.sh /opt/kafka/config/server.properties
/opt/kafka/bin/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-consumer-group
kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group my-consumer-group
| 参数 | 说明 |
|---|---|
--bootstrap-server |
Kafka broker 地址 |
--topic |
消费的 topic |
--group |
消费者组(影响 offset) |
--from-beginning |
从最早消息消费 |
--max-messages |
消费多少条后退出 |
--partition |
指定分区 |
--offset |
指定 offset |
示例:
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--partition 0 \
--offset 10
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>3.6.0</version>
</dependency>
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "my-group");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
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.printf("offset=%d, key=%s, value=%s%n",
record.offset(), record.key(), record.value());
}
}
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())
firewall-cmd --list-all
server.propertieslisteners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://<服务器IP>:9092
--from-beginning如果你能告诉我:
我可以给你更精确的配置示例。