( 二 )、Kafka 下載安裝
參考Kafka快速入門: https://kafka.apache.org/documentation/#quickstart
下載
官方下載: https://kafka.apache.org/downloads.html
官方推薦下載scala 2.13版本的: https://dlcdn.apache.org/kafka/3.0.0/kafka_2.13-3.0.0.tgz

1、下載並解壓
> tar -zxvf kafka_2.13-3.0.0.tgz > cd kafka_2.13-3.0.0
2: 啟動服務
注意:你的本地環境必須安裝有Java 8+
2.1、運行kafka需要使用Zookeeper,所以你需要先啟動Zookeeper,如果你沒有Zookeeper,你可以使用kafka自帶打包和配置好的Zookeeper。
> cd kafka_2.13-3.0.0/
> ./bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
2.2、啟動kafka服務
> ./bin/kafka-server-start.sh -daemon config/server.properties &
一旦所有服務成功啟動,那Kafka已經可以使用了。
3: 創建一個主題(topic)
創建一個名為“test”的Topic,只有一個分區和一個備份:
> ./bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic test
創建好之后,可以通過運行以下命令,查看已創建的topic信息:
> ./bin/kafka-topics.sh --describe --topic test --bootstrap-server localhost:9092 Topic:test PartitionCount:1 ReplicationFactor:1 Configs: Topic: test Partition: 0 Leader: 0 Replicas: 0 Isr: 0
或者,除了手工創建topic外,你也可以配置你的broker,當發布一個不存在的topic時自動創建topic。配置自動創建topic時設置默認的分區和副本數:
在server.properties中配置:
# 自動創建主題 auto.create.topics.enable=true # 默認主題的分區數 num.partitions=8 # 默認分區副本 default.replication.factor=3
注意:default.replication.factor:默認分區副本數不得超過kafka節點數(你想,副本數如果一個節點放2份,意義就沒了),每個節點都需要配置,然后重啟即可。
4: 發送消息
Kafka提供了一個命令行的工具,可以從輸入文件或者命令行中讀取消息並發送給Kafka集群。每一行是一條消息。運行 producer(生產者),然后在控制台輸入幾條消息到服務器。
> ./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test This is a message This is another message
5: 消費消息
Kafka也提供了一個消費消息的命令行工具,將存儲的信息輸出出來,新打開一個命令控制台,輸入:> ./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning This is a message This is another message
