Kafka命令大全详解(2026最新版)

Kafka是核心中间件,下面我详解Kafka命令大全@mikechen

一、Topic 管理(6 个)
Kafka 的核心资源就是 Topic,这一层命令最基础也最常用。
1. 创建 Topic

kafka-topics.sh --create \
--bootstrap-server localhost:9092 \
--replication-factor 3 \
--partitions 6 \
--topic test-topic

关键点:

  • replication-factor:副本数(高可用核心);
  • partitions:并发能力核心指标(决定吞吐);

2. 查看所有 Topic

kafka-topics.sh --list --bootstrap-server localhost:9092

3. 查看 Topic 详情

kafka-topics.sh --describe \
--topic test-topic \
--bootstrap-server localhost:9092

重点看:

  • Leader
  • ISR(同步副本)
  • Partition 分布

4. 删除 Topic

kafka-topics.sh --delete \
--topic test-topic \
--bootstrap-server localhost:9092

⚠️ 需要开启:

delete.topic.enable=true

5. 修改分区数(只能增加)

kafka-topics.sh --alter \
--topic test-topic \
--partitions 10 \
--bootstrap-server localhost:9092

6. 修改 Topic 配置

kafka-configs.sh --alter \
--entity-type topics \
--entity-name test-topic \
--add-config retention.ms=86400000 \
--bootstrap-server localhost:9092

二、Producer / Consumer(5 个)
用于调试、测试、排查问题。
7. 启动生产者

kafka-console-producer.sh \
--broker-list localhost:9092 \
--topic test-topic

8. 启动消费者

kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--from-beginning

9. 指定消费组消费

kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--group test-group

10. 查看消费组列表

kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--list

11. 查看消费组状态(非常重要🔥)

kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group test-group

关键指标:

  • LAG(是否堆积);
  • CURRENT-OFFSET;
  • LOG-END-OFFSET;

👉 面试高频点:如何判断 Kafka 是否积压,就是看 LAG。

三、消费组管理(3 个)
12. 重置消费位移

kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--group test-group \
--reset-offsets \
--to-earliest \
--execute \
--topic test-topic

常用策略:

  • --to-earliest
  • --to-latest
  • --shift-by

13. 删除消费组

kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--delete \
--group test-group

14. 查看某 Topic 的消费情况

kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--all-groups | grep test-topic

四、Broker / 集群管理(3 个)
15. 查看 Broker API 版本

kafka-broker-api-versions.sh \
--bootstrap-server localhost:9092

16. 查看集群信息

kafka-topics.sh \
--describe \
--bootstrap-server localhost:9092

(也可配合 zookeeper-shell 在旧版本中使用)

17. Leader 选举(重要🔥)

kafka-leader-election.sh \
--bootstrap-server localhost:9092 \
--election-type preferred \
--all-topic-partitions

👉 用于:

  • Broker 宕机恢复
  • 分区 Leader 不均衡

五、数据与性能工具(2 个)
18. 性能测试(Producer)

kafka-producer-perf-test.sh \
--topic test-topic \
--num-records 1000000 \
--record-size 100 \
--throughput 10000 \
--producer-props bootstrap.servers=localhost:9092

19. 性能测试(Consumer)

kafka-consumer-perf-test.sh \
--bootstrap-server localhost:9092 \
--topic test-topic \
--messages 1000000

评论交流
    说说你的看法