温馨提示×

Ubuntu怎么修改Kafka参数

小樊
38
2026-08-02 16:20:17
栏目: 智能运维

Ubuntu 上修改 Kafka 参数,通常是通过修改 Kafka 的 配置文件启动时指定的参数 来完成。下面按常见场景给你一个完整说明(适用于 Kafka 2.x / 3.x,Ubuntu 20.04/22.04)。


一、Kafka 主要配置文件位置

Kafka 配置文件一般在:

cd /opt/kafka/config
# 或
cd ~/kafka/config

常见配置文件:

文件 作用
server.properties Broker 核心配置(最常用)
producer.properties 生产者默认配置
consumer.properties 消费者默认配置
zookeeper.properties ZooKeeper 配置(老版本)

二、修改 Kafka Broker 参数(最常见)

1️⃣ 编辑 server.properties

sudo vim /opt/kafka/config/server.properties

常见需要修改的参数:

# Broker ID
broker.id=0

# 监听地址(非常重要)
listeners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://<服务器IP>:9092

# 日志目录
log.dirs=/var/lib/kafka-logs

# 分区数(默认)
num.partitions=3

# 副本数
default.replication.factor=2

# 自动创建 topic
auto.create.topics.enable=true

# 日志保留时间(小时)
log.retention.hours=168

# 单日志段大小
log.segment.bytes=1073741824

✅ 修改完成后保存


2️⃣ 重启 Kafka 使配置生效

# 停止 Kafka
/opt/kafka/bin/kafka-server-stop.sh

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

或(systemd 方式):

sudo systemctl restart kafka

三、修改 Topic 级别参数(无需重启 Kafka)

1️⃣ 查看 Topic 配置

kafka-configs.sh --bootstrap-server localhost:9092 \
--entity-type topics \
--entity-name test-topic \
--describe

2️⃣ 修改 Topic 参数

例如修改 数据保留时间

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

常用参数:

参数 含义
retention.ms 数据保留时间
segment.bytes 段文件大小
cleanup.policy delete / compact
max.message.bytes 最大消息大小

四、修改 Producer / Consumer 参数

Producer 示例

vim /opt/kafka/config/producer.properties
bootstrap.servers=localhost:9092
acks=all
compression.type=lz4
batch.size=32768
linger.ms=10

启动生产者时指定:

kafka-console-producer.sh \
--broker-list localhost:9092 \
--topic test \
--producer.config /opt/kafka/config/producer.properties

Consumer 示例

vim /opt/kafka/config/consumer.properties
bootstrap.servers=localhost:9092
group.id=test-group
auto.offset.reset=earliest
enable.auto.commit=false

五、通过命令行参数(临时修改)

kafka-server-start.sh /opt/kafka/config/server.properties \
--override num.partitions=5 \
--override log.retention.hours=72

✅ 优先级高于配置文件
❌ 重启后失效


六、常见错误排查

❌ Kafka 启动后无法连接

检查:

listeners=PLAINTEXT://0.0.0.0:9092
advertised.listeners=PLAINTEXT://<真实IP>:9092

防火墙:

sudo ufw allow 9092

七、总结(快速流程)

# 1. 修改配置
vim /opt/kafka/config/server.properties

# 2. 重启 Kafka
systemctl restart kafka

# 3. 验证
kafka-broker-api-versions.sh --bootstrap-server localhost:9092

如果你愿意,可以告诉我:

  • Kafka 版本
  • 单机还是集群
  • 想改 哪个具体参数

我可以给你 精确配置示例

0