kafka基本原理

Apache Kafka是分布式發布-訂閱消息系統。它最初由LinkedIn公司開發,之后成為Apache項目的一部分。Kafka是一種快速、可擴展的、設計內在就是分布式的,分區的和可復制的提交日志服務。
現在很多開源分布式系統,例如Flume(數據實時分析),Storm(數據實時處理),Spark(內存數據處理),elasticsearch(全文檢索)
幾種分布式系統的對比

2017-05-05_095912.png

上圖介紹到的動態擴容,kafka目前是通過zookeeper來實現動態擴容的。zookeeper:一個提供分布式狀態管理,分布式配置管理,分布式鎖服務的集群。

AMQP協議

kafka借鑒AMQP協議進行開發
基本概念

  • 消費者(Consumer):從消息隊列中請求消息的客戶端應用程序
  • 生產者(Producer):向Broker發布消息的客戶端應用程序。
  • AMQP服務器端(Broker):用于接收生產者發送的消息并將消息路由給服務器中隊列。
  • 話題(Topic):是特定類型的消息流。消息是字節的有效負載(Payload),話題是消息的分類名或種子(Feed)名。類似新聞中的體育,娛樂,教育等概念。實際應用中往往一個業務一個主題。
  • 分區(Partition):topic中的消息按照分區來進行組織。其是kafka消息隊列組織的最小單位,一個分區可以看作一個FIFO隊列。


  • 備份(Replication):為了保證分布式高可靠性,kafka0.8開始對每個分區數據進行備份,防止一個Broker宕機導致分區數據中數據不可用

zookeeper配置

配置zookeeper需要先配置JAVA_HOME,注意下JAVA_HOME的配置方法如下:

JAVA_HOME=/usr/local/jdk1.8
export PATH=$JAVA_HOME/bin:$PATH

一般將系統的環境變量PATH寫在后面,因為系統讀取環境變量是從前往后找的,如果PATH中本來已經配置了JAVA_HOME,那么將其放在后面可以讓我們配置的JAVA_HOME優先被讀取到。
配置完java的環境變量后,需要配置zookeeper的conf/目錄下的zoo.cfg文件。將zoo_sample.cfg拷貝為zoo.cfg后,修改內容為下:

# The number of milliseconds of each tick
# 即下面計時方式的單位
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
# 20S,即這個時間內,集群中的機器都要啟動
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
# leader發送給follower的心跳超時時間
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
# 設置了zookeeper的dataDir以及DataLogDir,注意下這兩個目錄不要設
# 置為同一個,那樣的話會影響到zookeeper的性能。
dataDir=/home/eversilver/silverTest/kafka/zkData
# 這里存放的是zookeeper的事務日志,一般很多,需要定期的去清理,否
# 則產生很多垃圾,拖慢響應速度。官方文檔只給出了具體的清理方法
dataLogDir=/home/eversilver/silverTest/kafka/zookeeper/zkLog
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the 
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
# 設置zookeeper的服務器集群,集群一般設置為基數臺,當前機器對應
# 的集群id為1,有幾臺機器就配置幾行,這里有三臺機器。
# 機器名稱=機器IP:leader與follower之間通信端口:leader選舉的端口
# 注意,所以集群中的機器上面的端口應該對應相同
server.1=192.168.142.133:12888:13888
server.2=192.168.142.134:12888:13888
server.3=192.168.142.135:12888:13888

cfg文件配置完成后,在cfg文件中的dataDir目錄下新建一個myid文件,代表當前機器的id,這個id與上面server.后面的值相同即可:

eversilver@debian:/usr/local/zookeeper$ cat ~/silverTest/kafka/zookeeper/zkData/myid 
1

然后即可啟動本機,有幾臺機器即啟動幾臺:

eversilver@debian:/usr/local/zookeeper$ ./bin/zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
eversilver@debian:/usr/local/zookeeper$ jps
25846 Jps
25822 QuorumPeerMain
eversilver@debian:/usr/local/zookeeper$ 

這里啟動了三臺虛擬機上的zookeeper,可以通過zkServer.sh status來查看zookeeper運行狀態

# debian
eversilver@debian:/usr/local/zookeeper$ ./bin/zkServer.sh status
/usr/local/jdk1.8/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower

#debian2
eversilver@debian:/usr/local/zookeeper$ ./bin/zkServer.sh status
/usr/local/jdk1.8/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: leader

#debian3
eversilver@debian:/usr/local/zookeeper$ ./bin/zkServer.sh status
/usr/local/jdk1.8/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/local/zookeeper/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower

上面三臺機器中,debian2機器被選作了leader
leader主要作用是從客戶端接受并且響應請求
follower的主要作用:從leader同步數據,再leader關閉時,進行投票選舉出集群中的新的leader

集群搭建中的幾個重要的文件分別為:
myid文件:用于zookeeper機器間互相發現彼此
zoo.cfg:集群配置文件
log4j.properties文件:zk集群的日志輸出文件,同樣在conf目錄下
zkEnv.sh以及zkServer.sh:分別用于啟動環境配置以及集群啟動

注意,/bin目錄下的zkCleanUp.sh腳本可以快速的對zookeeper生成的日志進行清理,這里使用crontab定期執行其來進行清理。
crontab -l來查看定時任務是否存在,crontab -e對其進行編輯。這里編輯如下。其中主要需要進行配置的配置項有broker.id,port,hostname,log.dirs,numpartitions, message.max.bytes,default,replication.factor,replica.fetch.max.bytes以及zookeeper.connect

eversilver@debian:/usr/local/zookeeper$ crontab -e
# 分別代表分鐘,小時,月,年,星期幾,命令選項
0 0 * * 0 /usr/local/zookeeper/zkCleanup.sh

kafka集群搭建

解壓縮完成kafka后,打開配置文件server.properties.配置完成的的文件如下所示。

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# see kafka.server.KafkaConfig for additional details and defaults

############################# Server Basics #############################

# The id of the broker. This must be set to a unique integer for each broker.
# 類似zookeeper的myid字段
broker.id=1

# Switch to enable topic deletion or not, default value is false
#delete.topic.enable=true

############################# Socket Server Settings #############################

# The address the socket server listens on. It will get the value returned from 
# java.net.InetAddress.getCanonicalHostName() if not configured.
#   FORMAT:
#     listeners = security_protocol://host_name:port
#   EXAMPLE:
#     listeners = PLAINTEXT://your.host.name:9092
#listeners=PLAINTEXT://:9092


# Hostname and port the broker will advertise to producers and consumers. If not set, 
# it uses the value for "listeners" if configured.  Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
#advertised.listeners=PLAINTEXT://your.host.name:9092
port=19092
host.name=192.168.128.128
# The number of threads handling network requests
num.network.threads=3

# The number of threads doing disk I/O
# 設置成多個的時候一般下面的logDir也設置成多個,這樣一個線程處理一個目錄,性能會好很多
# 注意下面的多個目錄往往以逗號來分割
num.io.threads=8

# The send buffer (SO_SNDBUF) used by the socket server,主要為了提高性能
socket.send.buffer.bytes=102400

# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400

# The maximum size of a request that the socket server will accept (protection against OOM)
# 這個數不能超過java的堆棧大小
socket.request.max.bytes=104857600


############################# Log Basics #############################

# A comma seperated list of directories under which to store log files
log.dirs=/home/eversilver/silverTest/kafka/kafka/kafkaLogs

# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
# topic分區數
num.partitions=2

# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1

############################# Log Flush Policy #############################

# Messages are immediately written to the filesystem but by default we only fsync() to sync
# the OS cache lazily. The following configurations control the flush of data to disk.
# There are a few important trade-offs here:
#    1. Durability: Unflushed data may be lost if you are not using replication.
#    2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
#    3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks.
# The settings below allow one to configure the flush policy to flush data after a period of time or
# every N messages (or both). This can be done globally and overridden on a per-topic basis.

# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000

# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000

############################# Log Retention Policy #############################

# The following configurations control the disposal of log segments. The policy can
# be set to delete segments after a period of time, or after a given size has accumulated.
# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
# from the end of the log.

# The minimum age of a log file to be eligible for deletion
# 消息失效期,7天
log.retention.hours=168

# kafka每條消息存放的最大大小
message.max.byte=5048576
#kafka集群保存消息的默認份數(副本數)
default.replication.factor=2
# 取消息的最大字節數,設置為5M
replica.fetch.max.bytes=5048576


# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining
# segments don't drop below log.retention.bytes.
#log.retention.bytes=1073741824

# The maximum size of a log segment file. When this size is reached a new log segment will be created.
# 超過這個大小就不再追加文件,而是新啟動一個文件
log.segment.bytes=1073741824

# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
# 每隔這么多毫秒查看是否有失效的消息,(上面是168小時)。有的話就刪除消息
log.retention.check.interval.ms=300000
# 是否啟用log壓縮
log.cleaner.enable=false

############################# Zookeeper #############################

# Zookeeper connection string (see zookeeper docs for details).
# This is a comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002".
# You can also append an optional chroot string to the urls to specify the
# root directory for all kafka znodes.
zookeeper.connect=192.168.128.128:2181,192.168.128.129:2181,192.168.128.130:2181

# Timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=6000

三個機器都配置完成后,可以使用./bin/kafka-server.sh -daemon ./config/servers.properties命令來打開kafka。打開命令后使用jps查看運行狀態如下:

eversilver@debian:/usr/local/kafka$ jps
10273 Jps
8994 QuorumPeerMain
10026 Kafka

下面可以使用一個例子查看配置是否正確。創建一個主題。命令如下:

eversilver@debian:/usr/local/kafka$ ./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 2 --partitions 1 --topic test
Created topic "test".

查看當前的主題

eversilver@debian:/usr/local/kafka$ bin/kafka-topics.sh --list --zookeeper localhost:2181
test #當前的test主題已經存在

啟動一個kafka的生產者:

eversilver@debian:/usr/local/kafka$ bin/kafka-console-producer.sh --broker-list 192.168.128.128:19092 --topic test

另一臺機器上啟動一個kafka的消費者

eversilver@debian:/usr/local/kafka$ bin/kafka-console-consumer.sh --bootstrap-server 192.168.128.129:19092 --topic test --from-beginning

當在生產者端輸入"hello"后,消費者端也會正常顯示"hello"
同樣可以通過命令查看topic的基本信息:

eversilver@debian:/usr/local/kafka$ ./bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test
Topic:test  PartitionCount:1    ReplicationFactor:1 Configs:
Topic: test Partition: 0    Leader: 1   Replicas: 1 Isr: 1

kafka的日志目錄下的server.log是kafka集群的機器進行leader切換時產生的日志。state.change.log日志。controller.log存放的是kafka集群中的controller所產生的日志。

zookeeper運行之后可以使用 ./bin/zkCli.sh -server 127.0.0.1:2181 可以進入zookeeper的客戶端,ls / 命令顯示的zookeeper內部狀態如下所示。

[zk: 127.0.0.1:2181(CONNECTED) 0] ls /
[admin, brokers, cluster, config, consumers, controller, controller_epoch, isr_change_notification, zookeeper]

上面的所有文件除了zookeeper文件夾是zookeeper產生的其他均為kafka所產生的。可以查看broker下面的相關信息。

[zk: 127.0.0.1:2181(CONNECTED) 12] ls /brokers
[ids, seqid, topics]
[zk: 127.0.0.1:2181(CONNECTED) 13] ls /brokers/ids
[1, 2]
[zk: 127.0.0.1:2181(CONNECTED) 14] ls /brokers/ids/1
[]
[zk: 127.0.0.1:2181(CONNECTED) 15] get /brokers/ids/1
{"jmx_port":-1,"timestamp":"1494050585414","endpoints":["PLAINTEXT://192.168.128.128:19092"],"host":"192.168.128.128","version":3,"port":19092}

上面顯示了ids1的啟動時間,端口號,版本

 [zk: 127.0.0.1:2181(CONNECTED) 16] ls /brokers/topics
[__consumer_offsets, my-first-kafka-topic, test]
[zk: 127.0.0.1:2181(CONNECTED) 17] get /brokers/topics/test
{"version":1,"partitions":{"0":[1]}}

上面顯示了當前存在的所有的topic。例如其中的test topic,只有一個分區 ,版本是1.

kafka的config文件夾下的,consumer.properties配置項如下:

eversilver@debian:/usr/local/kafka$ cat ./config/consumer.properties 
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# see kafka.consumer.ConsumerConfig for more details

# Zookeeper connection string
# comma separated host:port pairs, each corresponding to a zk
# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"
zookeeper.connect=127.0.0.1:2181

# timeout in ms for connecting to zookeeper
zookeeper.connection.timeout.ms=6000

# consumer group id
# 用來組合一個topic下面的多個partition,如果一個topic有兩個group-id,那么
# 一個group-id對應于一個consumer組。不同consumer組可以復制消費這個topic的
# 消息。即一個topic消息可以被兩個group拿兩次。
group.id=test-consumer-group

#consumer timeout
#consumer.timeout.ms=5000

kafka的config文件夾下的,producer.properties配置項也需要注意些。
注意,kafka的配置項優先級最高的是程序中設置的配置項,其次是shell中開始命令時的配置項,最低的是配置文件中設置的配置項。

相關資料:
http://kafka.apache.org/quickstart : kafka快速開始
http://kafka.apache.org/documentation/#brokerconfigs : broker配置項以及其他的配置項。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評論 6 537
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,772評論 3 422
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,960評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,350評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,549評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,104評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,914評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,089評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,340評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,834評論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,106評論 2 375

推薦閱讀更多精彩內容