Kafka 日常操作
# Kafka 日常操作指南
本文档整理了 Kafka 常用的运维操作命令,包括主题(Topic)管理、消费组管理、集群管理等方面。
# Topic 管理操作
# 创建 Topic
kafka-topics.sh --create \
--zookeeper localhost:2181 \
--replication-factor 3 \
--partitions 10 \
--topic test
1
2
3
4
5
2
3
4
5
# Topic 查看操作
查看所有 topic 列表:
kafka-topics.sh --list --zookeeper localhost:2181
1
查看指定 topic 详细信息:
kafka-topics.sh --zookeeper localhost:2181 --describe --topic test
1
# Topic 修改操作
增加 topic 分区数:
kafka-topics.sh --zookeeper localhost:2181 --alter --topic test --partitions 10
1
设置数据保留大小(例如限制为 60G):
kafka-configs.sh --zookeeper localhost:2181 \
--alter --entity-type topics \
--entity-name test \
--add-config retention.bytes=60737418240
1
2
3
4
2
3
4
设置数据保留时间(例如保留3天):
kafka-configs.sh --zookeeper localhost:2181 \
--alter --entity-type topics \
--entity-name test \
--add-config retention.ms=259200000
1
2
3
4
2
3
4
# 删除 Topic
kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
1
注意:删除操作需要在 server.properties 中配置 delete.topic.enable=true
,否则只会将 topic 标记为待删除状态,不会实际释放磁盘空间。
# 消息生产和消费
# 消费 Topic 数据
kafka-console-consumer.sh --bootstrap-server localhost:9092 \
--topic test \
--from-beginning
1
2
3
2
3
# 生产数据到 Topic
kafka-console-producer.sh --broker-list localhost:9092 --topic test
1
# 消费组管理
# 查看消费组列表
kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list
1
# 查看消费组详情
kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--describe --group mygroup
1
2
2
# 删除消费组
kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--delete --group test
1
2
2
# 集群管理
# 查看集群节点
通过 ZooKeeper 客户端查看 broker 节点:
# 1. 连接到 ZooKeeper
zkCli.sh -server localhost:2181
# 2. 查看 broker 列表
ls /brokers/ids
1
2
3
4
5
2
3
4
5
# 调整副本分配
创建副本重分配配置文件 (replication.json):
{
"version": 1,
"partitions": [
{
"topic": "test_topic",
"partition": 0,
"replicas": [1, 2, 3]
}
]
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
执行副本重分配:
kafka-reassign-partitions.sh --zookeeper localhost:2181 \
--reassignment-json-file replication.json \
--execute
1
2
3
2
3
# 监控技巧
实时监控消费组状态:
watch -d kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--describe --group mygroup
1
2
2
注意事项:
- 以上命令中的主机名、端口需要根据实际环境修改
- 建议在进行关键操作前先备份相关数据
- 生产环境中的配置修改需要经过充分测试
上次更新: 4/24/2025