测试 Kafka 服务可以从连通性、基本功能、性能、稳定性等多个层面进行。下面按由浅入深的方式给你一套完整实用的测试方案,适用于开发、测试、运维场景。
你需要知道:
host:port(如 localhost:9092)telnet / nc 测试端口telnet localhost 9092
或
nc -vz localhost 9092
✅ 能连上说明网络没问题
❌ 连不上检查:
kafka-broker-api-versions.sh --bootstrap-server localhost:9092
✅ 返回 API 版本说明 Kafka 正常
kafka-topics.sh \
--bootstrap-server localhost:9092 \
--create \
--topic test-topic \
--partitions 3 \
--replication-factor 1
查看 Topic:
kafka-topics.sh --bootstrap-server localhost:9092 --describe --topic test-topic
kafka-console-producer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic
手动输入消息:
hello kafka
test message
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--from-beginning
✅ 能看到刚才发送的消息说明 Kafka 基本功能正常
Kafka 自带性能测试工具,非常实用。
kafka-producer-perf-test.sh \
--topic test-topic \
--num-records 100000 \
--record-size 1024 \
--throughput -1 \
--producer-props bootstrap.servers=localhost:9092
关注指标:
kafka-consumer-perf-test.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--messages 100000
kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--group test-group
再启动一个相同 group 的 consumer,观察:
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<>("test-topic", "key", "value"));
producer.close();
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test-group");
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"));
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
| 现象 | 可能原因 |
|---|---|
| 连接超时 | broker 未启动 / 端口未开放 |
| topic 不存在 | auto.create.topics.enable=false |
| 消费不到消息 | consumer group offset 问题 |
| 性能低 | 分区数少 / 磁盘慢 |
✅ 快速验证
端口 → broker api → 创建 topic → 生产 → 消费
✅ 性能验证
producer perf test → consumer perf test
✅ 生产级验证
多副本 → consumer group → 容错 → 监控
如果你愿意,我可以:
你现在是在 本地 / 测试环境 / 生产环境 测试 Kafka?