Centos安装Kafka

1. 准备环境

  • 操作系统:CentOS7
  • 前置依赖: JDK 1.8+(Kafka 依赖 Java) Zookeeper(Kafka 3.4 开始可以内置 KRaft,不再必须用 Zookeeper;这里我给你传统 Zookeeper + Kafka 的方式)


2. 安装 JDK

# 安装 JDK 1.8
sudo yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel

# 验证
java -version


3. 下载并解压 Kafka

去 Apache 官网下载最新版本(比如 3.7.0):

cd /usr/local
wget https://downloads.apache.org/kafka/3.7.0/kafka_2.13-3.7.0.tgz
tar -xzf kafka_2.13-3.7.0.tgz
mv kafka_2.13-3.7.0 kafka
cd kafka


4. 启动 Zookeeper

Kafka 默认需要依赖 Zookeeper:

# 启动 Zookeeper
bin/zookeeper-server-start.sh config/zookeeper.properties

(建议用 -daemon 后台运行)



5. 启动 Kafka Broker

另开一个终端:

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

同样可以用 -daemon 后台运行:

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


6. 测试 Kafka

创建一个 Topic

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

查看 Topic

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

生产消息

bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test

输入内容,比如:

hello kafka

消费消息

另开一个终端:

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

会看到刚才的 hello kafka



7. 后台运行 & 服务化

建议配置 systemd 服务:

/etc/systemd/system/kafka.service

[Unit]
Description=Apache Kafka server
After=network.target zookeeper.service

[Service]
Type=simple
User=root
ExecStart=/usr/local/kafka/bin/kafka-server-start.sh /usr/local/kafka/config/server.properties
ExecStop=/usr/local/kafka/bin/kafka-server-stop.sh
Restart=on-abnormal

[Install]
WantedBy=multi-user.target

启动 Kafka 服务

systemctl daemon-reload
systemctl enable kafka
systemctl start kafka
systemctl status kafka


文章标签:

评论(0)