在 Ubuntu 上使用 Kafka 创建(设)主题,通常分为 使用命令行 和 通过配置文件/代码 两种方式。下面以最常见的 Kafka 命令行方式 为主,适合刚安装好 Kafka 的场景。
/opt/kafka 或 ~/kafka)# 启动 Zookeeper(老版本)
bin/zookeeper-server-start.sh config/zookeeper.properties
# 启动 Kafka
bin/kafka-server-start.sh config/server.properties
Kafka 新版本(2.8+)可使用 KRaft 模式,不依赖 Zookeeper。
cd ~/kafka
# 或
cd /opt/kafka
bin/kafka-topics.sh \
--create \
--topic test-topic \
--bootstrap-server localhost:9092 \
--partitions 3 \
--replication-factor 1
参数说明:
--topic:主题名--partitions:分区数--replication-factor:副本数(单机只能为 1)--bootstrap-server:Kafka 地址✅ 成功会看到:
Created topic test-topic.
bin/kafka-topics.sh --list --bootstrap-server localhost:9092
查看某个主题详情:
bin/kafka-topics.sh --describe --topic test-topic --bootstrap-server localhost:9092
bin/kafka-topics.sh --delete --topic test-topic --bootstrap-server localhost:9092
⚠️ 需确保:
delete.topic.enable=true
(新版 Kafka 默认开启)
bin/kafka-topics.sh \
--alter \
--topic test-topic \
--partitions 5 \
--bootstrap-server localhost:9092
⚠️ 分区只能增加,不能减少
bin/kafka-console-producer.sh \
--topic test-topic \
--bootstrap-server localhost:9092
bin/kafka-console-consumer.sh \
--topic test-topic \
--from-beginning \
--bootstrap-server localhost:9092
command not found确认路径是否正确,或使用:
./bin/kafka-topics.sh
localhost:9092 写错listeners 配置问题如果你用的是:
可以告诉我,我可以给你对应示例。