温馨提示×

ubuntu kafka如何配置主题

小樊
39
2026-09-17 18:32:04
栏目: 智能运维

在 Ubuntu 上配置 Kafka 主题(Topic),通常分为 命令行方式(最常用)和 配置文件方式(主要是 broker 和默认参数)。下面按实际使用场景给你说明。


一、前提条件(Ubuntu 上已安装 Kafka)

假设你的 Kafka 安装在:

/opt/kafka

或

~/kafka

并且 Kafka 服务已经启动:

# 启动 Zookeeper(老版本)
bin/zookeeper-server-start.sh config/zookeeper.properties

# 启动 Kafka
bin/kafka-server-start.sh config/server.properties

Kafka 2.8+ 可不使用 Zookeeper(KRaft 模式),命令略有不同。


二、使用命令行创建主题(最常用)

1️⃣ 创建一个主题

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

参数说明:

参数 说明
--topic 主题名称
--partitions 分区数
--replication-factor 副本数(不能大于 broker 数量)
--bootstrap-server Kafka 地址

2️⃣ 查看主题列表

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

3️⃣ 查看主题详情

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

4️⃣ 删除主题

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

⚠️ 需要配置:

delete.topic.enable=true

(Kafka 新版本默认已开启)


三、修改主题配置(动态配置)

1️⃣ 修改分区数(只能增加)

bin/kafka-topics.sh \
  --alter \
  --topic test-topic \
  --partitions 5 \
  --bootstrap-server localhost:9092

2️⃣ 修改主题级别参数(如保留时间)

bin/kafka-configs.sh \
  --alter \
  --topic test-topic \
  --bootstrap-server localhost:9092 \
  --add-config retention.ms=86400000

常见配置:

配置项 说明
retention.ms 消息保留时间(毫秒)
retention.bytes 分区最大大小
cleanup.policy delete / compact
max.message.bytes 单条消息最大大小

四、通过配置文件设置默认主题参数(Ubuntu 服务端)

编辑 Kafka 配置文件:

vim config/server.properties

常见默认配置:

num.partitions=3
default.replication.factor=1
log.retention.hours=168
log.segment.bytes=1073741824

修改后需重启 Kafka:

bin/kafka-server-stop.sh
bin/kafka-server-start.sh config/server.properties

五、自动创建主题(不推荐生产)

auto.create.topics.enable=true

⚠️ 生产环境建议关闭,防止误建主题。


六、示例:一个完整流程

# 创建
bin/kafka-topics.sh --create --topic order --partitions 3 --replication-factor 1 --bootstrap-server localhost:9092

# 生产消息
bin/kafka-console-producer.sh --topic order --bootstrap-server localhost:9092

# 消费消息
bin/kafka-console-consumer.sh --topic order --from-beginning --bootstrap-server localhost:9092

如果你告诉我:

  • Kafka 版本(2.x / 3.x)
  • 是否使用 Zookeeper
  • 单机还是集群

我可以给你更精确的 Ubuntu 配置示例。

0 踩