一、kafka是什麼
Kafka是一個分佈式的、可分區的、可複製的消息系統。它提供了普通消息系統的功能,但具有自己獨特的設計。
這個獨特的設計是什麼樣的呢?
首先讓我們看幾個基本的消息系統術語:
Kafka將消息以topic爲單位進行歸納。
將向Kafka topic發佈消息的程序成爲producers.
將預訂topics並消費消息的程序成爲consumer.
Kafka以集羣的方式運行,可以由一個或多個服務組成,每個服務叫做一個broker.
producers通過網絡將消息發送到Kafka集羣,集羣向消費者提供消息,如下圖所示:
客戶端和服務端通過TCP協議通信。Kafka提供了Java客戶端,並且對多種語言都提供了支持。
二、安裝kafka
前提:要安裝jdk
1、去這個頁面下載kafka http://kafka.apache.org/downloads.html,我這邊下載的是二進制的,不需要自己編譯,也可以下載源碼版,自己編譯安裝
2、下載安裝
cd /download
wget https://www.apache.org/dyn/closer.cgi?path=/kafka/2.0.0/kafka_2.12-2.0.0.tgz
tar -zxvf kafka_2.11-2.0.0.tgz
cd /download/kafka_2.11-2.0.0/config
編輯 監聽的端口,讓生產者監聽9092端口
vi server.properties
消費者默認監聽2182端口,也可以自己去修改
vi zookeeper.properties
三、開啓測試
1、開啓
cd /download/kafka_2.11-2.0.0
開一個終端1啓動zookeeper (這裏不懂zookeep是什麼,可以看我上一篇博客)
./bin/zookeeper-server-start.sh config/zookeeper.properties
開一個終端2啓動啓動kafka
./bin/kafka-server-start.sh config/server.properties
開一個終端4啓動測試的生產者,並監聽topic的test
./bin/kafka-console-producer.sh --broker-list 127.0.0.1:9092 --topic test
開一個終端3啓動測試的消費者,並監聽topic的test(注意新版的要用--bootstrap-server,舊版的用--zookeeper)
./bin/kafka-console-consumer.sh --bootstrap-server localhost:2181 --topic test --from-beginning
其他操作指令:
a、創建一個test的話題:
bin
/kafka-topics
.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic
test
b、查詢話題
bin
/kafka-topics
.sh --list --zookeeper localhost:2181
具體可以看:
http://kafka.apache.org/quickstart
此時
在終端4 輸入信息,在終端3可以看到
注意:啓動時可能會有一些問題,比如端口占用,等等,不要慌,慢慢來,看報錯信息,百度百度,你會成功的,不懂的可以留言給我
2、設置多代理集羣
複製兩個server.properties
cp
config
/server
.properties config
/server-1
.properties
cp
config
/server
.properties config
/server-2
.properties
分別編輯兩個文件
config/server-1.properties:
broker.id=1
listeners=PLAINTEXT://:9093
log.dirs=/tmp/kafka-logs-1
config/server-2.properties:
broker.id=2
listeners=PLAINTEXT://:9094
log.dirs=/tmp/kafka-logs-2
啓動兩個新節點
終端5:bin/kafka-server-start
.sh config
/server-1
.properties
終端6:bin
/kafka-server-start
.sh config
/server-2
.properties
創建一個新的話題作爲這個3個代理的replication-factor
開一個終端向生產者寫入信息
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my-replicated-topic
>my test message 1
>my test message 2
>my test message 3
打開終端用消費者獲取信息
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my-replicated-topic --from-beginning
bin/kafka-console-consumer.sh --bootstrap-server localhost:9093 --topic my-replicated-topic --from-beginning
bin/kafka-console-consumer.sh --bootstrap-server localhost:9094 --topic my-replicated-topic --from-beginning
可以測試容錯能力
1 2 3 |
|
bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic PartitionCount:1 ReplicationFactor:3 Configs:
Topic: my-replicated-topic Partition: 0 Leader: 2 Replicas: 1,2,0 Isr: 2,0
雖然最初寫的leader已經掛掉。但是這些信息仍然可以用來消費
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --from-beginning --topic my-replicated-topic
>my test message 1
>my test message 2
>my test message 3