Kafka 提供了豐富的 shell 命令工具,位于 Kafka 安裝目錄的?bin/
?目錄下(Windows 系統為?bin/windows/
)。這些命令用于管理主題、生產者、消費者、分區等核心組件。以下是常用的 Kafka shell 操作大全:
一、主題(Topic)操作
1. 創建主題
# 創建一個名為 test-topic 的主題,3個分區,2個副本
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--create \--topic test-topic \--partitions 3 \--replication-factor 2
--bootstrap-server
:指定 Kafka 集群地址(broker 列表)--partitions
:分區數量(提高并行度)--replication-factor
:副本數量(提高可用性,不能超過 broker 數量)
2. 查看所有主題
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--list
3. 查看主題詳情
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--describe \--topic test-topic
輸出包含分區數、副本分布、ISR(同步副本)等信息。
4. 修改主題(僅支持分區數增加)
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--alter \--topic test-topic \--partitions 5 # 只能增加,不能減少
5. 刪除主題
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--delete \--topic test-topic
- 需確保?
server.properties
?中?delete.topic.enable=true
(默認開啟)
二、生產者(Producer)操作
1. 啟動控制臺生產者
# 向 test-topic 發送消息(輸入內容后按回車發送)
bin/kafka-console-producer.sh --bootstrap-server localhost:9092 \--topic test-topic
2. 帶鍵值對的生產者
# 發送格式為 "key:value" 的消息(需指定分隔符)
bin/kafka-console-producer.sh --bootstrap-server localhost:9092 \--topic test-topic \--property "parse.key=true" \--property "key.separator=:"
輸入示例:user1:hello
(key 為 user1,value 為 hello)
三、消費者(Consumer)操作
1. 啟動控制臺消費者(從最新消息開始消費)
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \--topic test-topic
2. 從最早消息開始消費
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \--topic test-topic \--from-beginning
3. 消費指定分區的消息
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \--topic test-topic \--partition 0 # 消費第0個分區
4. 帶消費組的消費者
# 加入名為 test-group 的消費組
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 \--topic test-topic \--group test-group
四、消費組(Consumer Group)操作
1. 查看所有消費組
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \--list
2. 查看消費組詳情
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \--describe \--group test-group
輸出包含:
- 消費組 ID
- 主題名稱
- 分區分配情況
- 當前消費偏移量(CURRENT-OFFSET)
- 日志末尾偏移量(LOG-END-OFFSET)
- 未消費消息數(LAG)
3. 重置消費組偏移量
# 將 test-group 對 test-topic 的偏移量重置為最早
bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 \--group test-group \--topic test-topic \--reset-offsets \--to-earliest \--execute
其他重置選項:
--to-latest
:重置到最新--to-offset <offset>
:重置到指定偏移量--shift-by <number>
:相對當前偏移量移動(正數向前,負數向后)
五、分區(Partition)操作
1. 查看分區 Leader 分布
# 結合主題詳情查看
bin/kafka-topics.sh --bootstrap-server localhost:9092 \--describe \--topic test-topic | grep "Leader:"
六、其他常用操作
1. 查看 broker 元數據
bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092
2. 查看主題消息數量(近似值)
bin/kafka-run-class.sh kafka.tools.GetOffsetShell \--bootstrap-server localhost:9092 \--topic test-topic \--time -1 # -1 表示最新偏移量,-2 表示最早偏移量
計算總消息數:各分區最新偏移量之和。
七、Windows 系統注意事項
- 所有?
.sh
?命令替換為?.bat
(如?kafka-topics.bat
) - 路徑分隔符使用?
\
?而非?/
以上命令覆蓋了 Kafka 日常運維的核心場景,實際使用時需根據集群地址(--bootstrap-server
)和具體需求調整參數。