Kafka中Replicas復制備份機制
kafka將每個partition數據復制到多個server上,任何一個partition有一個leader和多個follower(可以沒有),備份的個數可以通過broker配置文件來設定(replication-factor的參數配置指定).leader處理所有的read-write請求,follower需要和leader保持同步.Follower和consumer一樣,消費消息並保存在本地日志中,leader負責跟蹤所有的follower狀態,如果follower"落后"太多或者失效,leader將會把它從replicas同步列表中刪除.當所有的follower都將一條消息保存成功,此消息才被認為是"committed",那么此時consumer才能消費它.即使只有一個replicas實例存活,仍然可以保證消息的正常發送和接收,只要zookeeper集群存活即可.
Kafka中的選舉
當leader失效時,需在followers中選取出新的leader,可能此時follower落后於leader,因此需要選擇一個"up-to-date"的follower.選擇follower時需要兼顧一個問題,就是新leader server上所已經承載的partition leader的個數,如果一個server上有過多的partition leader,意味着此server將承受着更多的IO壓力.在選舉新leader,需要考慮到"負載均衡".
常用命令
1、創建topics
./kafka-topics.sh --create --zookeeper chenx02:2181 --replication-factor 1 --partitions 1 --topic test
2、查看隊列列表
./kafka-topics.sh --list --zookeeper chenx02:2181
3、查看隊列明細
./kafka-topics.sh --describe --zookeeper chenx02:2181 --topic test
結果:
Topic:test PartitionCount:1 ReplicationFactor:1 Configs:
Topic: test Partition: 0 Leader: 2 Replicas: 2 Isr: 2
4、修改(test)隊列參數
./kafka-topics.sh --zookeeper chenx02:2181 --partition 3 --topic test --alter
結果:
Topic:test PartitionCount:3 ReplicationFactor:1 Configs:
Topic: test Partition: 0 Leader: 2 Replicas: 2 Isr: 2
Topic: test Partition: 1 Leader: 1 Replicas: 1 Isr: 1
Topic: test Partition: 2 Leader: 2 Replicas: 2 Isr: 2
5、創建多副本的隊列
./kafka-topics.sh --create --zookeeper chenx02:2181 --replication-factor 3 --partitions 4 --topic test_kafka
./kafka-topics.sh --describe --zookeeper chenx02:2181 --topic test_kafka
Topic:test_kafka PartitionCount:4 ReplicationFactor:3 Configs:
Topic: test_kafka Partition: 0 Leader: 1 Replicas: 1,3,2 Isr: 1,3,2
Topic: test_kafka Partition: 1 Leader: 2 Replicas: 2,1,3 Isr: 2,1,3
Topic: test_kafka Partition: 2 Leader: 3 Replicas: 3,2,1 Isr: 3,2,1
Topic: test_kafka Partition: 3 Leader: 1 Replicas: 1,2,3 Isr: 1,2,3
說明:
partiton: partion id
leader:當前負責讀寫的lead broker id
replicas:當前partition的所有replication broker list
isr:relicas的子集,只包含出於活動狀態的broker
6、刪除kafka的隊列[注意需要重啟kafka集群]
kafka-run-class.sh kafka.admin.DeleteTopicCommand --topic test_kafka --zookeeper chenx02:2181
7、查看不可用的分區
kafka-topics.sh --describe --unavailable-partitions --zookeeper chenx02:2181 --topic test_kafka
8、發送消息
./kafka-console-producer.sh --broker-list chenx02:9092 --topic test
9、消費消息
./kafka-console-consumer.sh --zookeeper chenx02:2181 --topic test --from-beginning