1. 程式人生 > >Kafka原理介紹及使用配置

Kafka原理介紹及使用配置

剛才只是啟動了單個broker,現在啟動有3個broker組成的叢集,這些broker節點也都是在本機上的:
首先為每個節點編寫配置檔案:
 
> cp config/server.properties config/server-1.properties
> cp config/server.properties config/server-2.properties
在拷貝出的新檔案中新增以下引數:
config/server-1.properties:
    broker.id=1
    port=9093
    log.dir=/tmp/kafka-logs-1
 
config/server-2.properties:
    broker.id=2
    port=9094
    log.dir=/tmp/kafka-logs-2
broker.id在叢集中唯一的標註一個節點,因為在同一個機器上,所以必須制定不同的埠和日誌檔案,避免資料被覆蓋。
 
We already have Zookeeper and our single node started, so we just need to start the two new nodes:
剛才已經啟動可Zookeeper和一個節點,現在啟動另外兩個節點:
> bin/kafka-server-start.sh config/server-1.properties &
...
> bin/kafka-server-start.sh config/server-2.properties &
...
建立一個擁有3個副本的topic:
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 3 --partitions 1 --topic my-replicated-topic
現在我們搭建了一個叢集,怎麼知道每個節點的資訊呢?執行“"describe topics”命令就可以了:
> 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: 1       Replicas: 1,2,0 Isr: 1,2,0
下面解釋一下這些輸出。第一行是對所有分割槽的一個描述,然後每個分割槽都會對應一行,因為我們只有一個分割槽所以下面就只加了一行。
leader:負責處理訊息的讀和寫,leader是從所有節點中隨機選擇的.
replicas:列出了所有的副本節點,不管節點是否在服務中.
isr:是正在服務中的節點.
在我們的例子中,節點1是作為leader執行。
向topic傳送訊息:
> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my-replicated-topic
...
my test message 1my test message 2^C 
消費這些訊息:
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic my-replicated-topic
...
my test message 1
my test message 2
^C
測試一下容錯能力.Broker 1作為leader執行,現在我們kill掉它:
> ps | grep server-1.properties7564 ttys002    0:15.91 /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java...
> kill -9 7564
另外一個節點被選做了leader,node 1 不再出現在 in-sync 副本列表中:
> bin/kafka-topics.sh --describe --zookeeper localhost:218192 --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 down掉了,但之前的訊息還是可以消費的:
> bin/kafka-console-consumer.sh --zookeeper localhost:2181 --from-beginning --topic my-replicated-topic
...
my test message 1
my test message 2
^C
看來Kafka的容錯機制還是不錯的。