Kafka研究【一】:bring up環境


kafka是干什么的,有和特性,我這里就不多說,詳情自己研究官方文檔

 

0. 背景介紹

我需要在三台機器上分別部署kafka broker的實例,構建成一個集群。
kafka的broker集群,是基於zookeeper作為協調器或者資源同步管理器的,主要是記錄High Level Offset標記信息的。 另外,zookeeper還用作broker的選主以及partition的選主。
三台機器上分別安裝zookeeper和kafka。

10.90.7.2    Linux localhost.localdomain 2.6.18-274.el5 #1 SMP Fri Jul 8 17:36:59 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux
10.90.2.101   Linux bogon 3.10.0-229.el7.x86_64 #1 SMP Thu Jan 29 18:37:38 EST 2015 x86_64 x86_64 x86_64 GNU/Linux
10.90.2.102    Linux localhost.localdomain 3.10.0-229.el7.x86_64 #1 SMP Thu Jan 29 18:37:38 EST 2015 x86_64 x86_64 x86_64 GNU/Linux

 

1. 軟件下載
下載kafka 1.0.1版本
https://www.apache.org/dyn/closer.cgi?path=/kafka/1.0.1/kafka_2.11-1.0.1.tgz
遵循我一貫的原則,為了生產環境的穩定性,不會去首先使用最新版本,當前這個是次新版本。最新的版本是1.1.0,Released March 28, 2018。
下載zookeeper 3.4.9
https://archive.apache.org/dist/zookeeper/zookeeper-3.4.9/zookeeper-3.4.9.tar.gz
這個是當前穩定運行的版本,是次新版,最新的版本,有幾個alpha和beta的,版本好最高達到3.5.4了。

 

2. 軟件安裝
2.1 zookeeper安裝,三台服務器構建最小集群,保證paxos的選主算法正常運行。配置很簡單,下面就只是將配置數據貼出來。

# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between 
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just 
# example sakes.
dataDir=/opt/shihuc/zookeeper-3.4.9/zkData/data
dataLogDir=/opt/shihuc/zookeeper-3.4.9/zkData/logs
# 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

server.1=10.90.7.2:2888:3888
server.2=10.90.2.101:2888:3888
server.3=10.90.2.102:2888:3888

注意,在每一台zookeeper所在的機器對應配置文件dataDir所在的路徑下創建myid,myid文件存放zookeeper服務器的編號(正如配置文件中server.x中的x,本案例中x是1,2,3)

 

啟動zookeeper,查看啟動腳本的幫助信息:

[root@localhost bin]# ./zkServer.sh 
ZooKeeper JMX enabled by default
Using config: /opt/shihuc/zookeeper-3.4.9/bin/../conf/zoo.cfg
Usage: ./zkServer.sh {start|start-foreground|stop|restart|status|upgrade|print-cmd}

正常啟動操作(三台機器,都做相同操作):

[root@localhost bin]# ./zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /opt/shihuc/zookeeper-3.4.9/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED

 

 檢查幾個zookeeper的狀態:

[root@localhost bin]# ./zkServer.sh status   #---10.90.7.2
ZooKeeper JMX enabled by default
Using config: /opt/shihuc/zookeeper-3.4.9/bin/../conf/zoo.cfg
Mode: leader
[root@localhost bin]# ./zkServer.sh status   #---10.90.2.101
ZooKeeper JMX enabled by default
Using config: /opt/shihuc/zookeeper-3.4.9/bin/../conf/zoo.cfg
Mode: follower
[root@localhost bin]# ./zkServer.sh status   #---10.90.2.102
ZooKeeper JMX enabled by default
Using config: /opt/shihuc/zookeeper-3.4.9/bin/../conf/zoo.cfg
Mode: follower

 

2.2 安裝kafka

安裝很簡單,直接將下載的kafka軟件的包解壓即可,然后配置一下config下面的server.properties文件,主要是修改log路徑以及zookeeper的監聽地址。然后運行bin下面的kafka-server-start.sh即可。

配置信息:

# 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.
broker.id=0

############################# 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 = listener_name://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

# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
#listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL

# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3

# The number of threads that the server uses for processing requests, which may include disk I/O
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)
socket.request.max.bytes=104857600


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

# A comma seperated list of directories under which to store log files
log.dirs=/opt/shihuc/kafka_2.11-1.0.1/logDir

# 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.
num.partitions=1

# 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

############################# Internal Topic Settings  #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended for to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=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 due to age
log.retention.hours=168

# A size-based retention policy for logs. Segments are pruned from the log unless the remaining
# segments drop below log.retention.bytes. Functions independently of log.retention.hours.
#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
log.retention.check.interval.ms=300000

############################# 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=10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181

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


############################# Group Coordinator Settings #############################

# The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance.
# The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms.
# The default value for this is 3 seconds.
# We override this to 0 here as it makes for a better out-of-the-box experience for development and testing.
# However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup.
group.initial.rebalance.delay.ms=0

啟動kafka服務:

[root@localhost bin]# nohup ./kafka-server-start.sh ../config/server.properties &

對三台機器都做broker的啟動操作,遇到下面的問題:

[2018-06-12 14:22:38,986] INFO [TransactionCoordinator id=0] Startup complete. (kafka.coordinator.transaction.TransactionCoordinator)
[2018-06-12 14:22:39,013] INFO Creating /brokers/ids/0 (is it secure? false) (kafka.utils.ZKCheckedEphemeral)
[2018-06-12 14:22:39,021] INFO Result of znode creation is: NODEEXISTS (kafka.utils.ZKCheckedEphemeral)
[2018-06-12 14:22:39,022] FATAL [KafkaServer id=0] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer) java.lang.RuntimeException: A broker is already registered on the path /brokers/ids/0. This probably indicates that you either have configured a brokerid that is already in use, or else you have shutdown this broker and restarted it fas ter than the zookeeper timeout so it appears to be re-registering. at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:440) at kafka.utils.ZkUtils.registerBrokerInZk(ZkUtils.scala:426) at kafka.server.KafkaHealthcheck.register(KafkaHealthcheck.scala:73) at kafka.server.KafkaHealthcheck.startup(KafkaHealthcheck.scala:53) at kafka.server.KafkaServer.startup(KafkaServer.scala:287) at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38) at kafka.Kafka$.main(Kafka.scala:92) at kafka.Kafka.main(Kafka.scala)
[2018-06-12 14:22:39,024] INFO [KafkaServer id=0] shutting down (kafka.server.KafkaServer)
[2018-06-12 14:22:39,025] INFO [SocketServer brokerId=0] Stopping socket server request processors (kafka.network.SocketServer)
[2018-06-12 14:22:39,034] INFO [SocketServer brokerId=0] Stopped socket server request processors (kafka.network.SocketServer)
[2018-06-12 14:22:39,034] INFO [Kafka Request Handler on Broker 0], shutting down (kafka.server.KafkaRequestHandlerPool)
[2018-06-12 14:22:39,036] INFO [Kafka Request Handler on Broker 0], shut down completely (kafka.server.KafkaRequestHandlerPool)
[2018-06-12 14:22:39,038] INFO [KafkaApi-0] Shutdown complete. (kafka.server.KafkaApis)
[2018-06-12 14:22:39,038] INFO [ExpirationReaper-0-topic]: Shutting down (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2018-06-12 14:22:39,149] INFO [ExpirationReaper-0-topic]: Stopped (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2018-06-12 14:22:39,149] INFO [ExpirationReaper-0-topic]: Shutdown completed (kafka.server.DelayedOperationPurgatory$ExpiredOperationReaper)
[2018-06-12 14:22:39,151] INFO [TransactionCoordinator id=0] Shutting down. (kafka.coordinator.transaction.TransactionCoordinator)
[2018-06-12 14:22:39,151] INFO [ProducerId Manager 0]: Shutdown complete: last producerId assigned 3000 (kafka.coordinator.transaction.ProducerIdManager)
[2018-06-12 14:22:39,152] INFO [Transaction State Manager 0]: Shutdown complete (kafka.coordinator.transaction.TransactionStateManager)
[2018-06-12 14:22:39,152] INFO [Transaction Marker Channel Manager 0]: Shutting down (kafka.coordinator.transaction.TransactionMarkerChannelManager)

錯誤原因是server.properties文件中的broker.id的值,在集群環境下重復了,即,一個kafka的集群環境下,broker.id的值是不能重復的,必須唯一。就算kafka服務在不同機器上

 

3. 驗證環境

3.1 創建一個topic

在10.90.2.102上操作:

[root@localhost bin]# ./kafka-topics.sh --create --zookeeper 10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181 --replication-factor 3 --partitions 1 --topic first
Created topic "first".

同一台機器上重復操作:

[root@localhost bin]# ./kafka-topics.sh --create --zookeeper 10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181 --replication-factor 3 --partitions 1 --topic first
Error while executing topic command : Topic 'first' already exists.
[2018-06-12 14:45:01,490] ERROR org.apache.kafka.common.errors.TopicExistsException: Topic 'first' already exists.
 (kafka.admin.TopicCommand$)

在10.90.7.2機器上創建相同的topic:

[root@localhost bin]# ./kafka-topics.sh --create --zookeeper 10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181 --replication-factor 3 --partitions 1 --topic first
Error while executing topic command : Topic 'first' already exists.
[2018-06-12 14:59:29,611] ERROR org.apache.kafka.common.errors.TopicExistsException: Topic 'first' already exists.
 (kafka.admin.TopicCommand$)

同一個名稱的topic,在一個kafka的集群環境下,不能重復創建

 

3.2 創建一個kafka的生產者

在10.90.2.101上操作:

[root@localhost bin]# ./kafka-console-producer.sh --broker-list 10.90.7.2:9092,10.90.2.101:9092,10.90.2.102:9092 --topic first
>
[2018-06-12 14:51:15,514] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:15,655] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 4 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:15,761] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 5 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:15,868] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 6 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:15,975] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 7 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:16,083] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 8 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2018-06-12 14:51:16,189] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 9 : {first=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)

經過反復測試驗證環境配置信息,最終參考了他人的經驗,是kafka的server.properties的配置錯誤。主要是下面的內容配置有問題:

listeners=PLAINTEXT://:9092

將這句注釋掉,然后在配置文件中添加下面的兩行配置,指明當前broker的地址:

port=9092
host.name=10.90.7.2 #依據具體的服務器,配置相應的服務器的IP地址即可。

 

修改后,再次重啟kafka服務,重新在某台服務器上啟動消息生產者服務,例如在10.90.2.102上:

[root@localhost bin]# ./kafka-console-producer.sh --broker-list 10.90.7.2:9092,10.90.2.101:9092,10.90.2.102:9092 --topic first
>hello
>good
>

然后在另外一台服務器上,啟動消息消費者,例如在10.90.7.2上:

[root@localhost bin]# ./kafka-console-consumer.sh --bootstrap-server 10.90.7.2:9092,10.90.2.101:9092,10.90.2.102:9092 --topic 
hello
good

到此為止,kafka生產者消費者,在控制台下消息收發正常,說明kafka的環境配置成功。

 

3.3 查看不同的topic下的broker信息

[root@localhost bin]# ./kafka-topics.sh --describe --zookeeper 10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181 --topic first
Topic:first     PartitionCount:1        ReplicationFactor:3     Configs:
        Topic: first    Partition: 0    Leader: 1       Replicas: 1,2,3 Isr: 1,2,3
[root@localhost bin]# ./kafka-topics.sh --describe --zookeeper 10.90.7.2:2181,10.90.2.101:2181,10.90.2.102:2181 --topic second
Topic:second    PartitionCount:2        ReplicationFactor:3     Configs:
        Topic: second   Partition: 0    Leader: 3       Replicas: 3,1,2 Isr: 3,2,1
        Topic: second   Partition: 1    Leader: 1       Replicas: 1,2,3 Isr: 1,2,3

這是輸出解釋。第一行給出了各個分區的概況,分區有幾個就有幾行分區詳細信息介紹。(我創建了兩個topic,一個是first,只有一個分區;一個是second,兩個分區)

Leader   是負責當前分區的所有讀寫請求。每個節點都將領導一個隨機選擇的分區。

Replicas   是節點列表,復制分區日志,不管他們是不是Leader或者不管它們是否還活着。

Isr        是in-sync的集合。這是Replicas列表當前還活着的子集。

 

 

總體來說,Kafka的環境構建,還是比較容易的,配置信息,相對來說,也比較容易理解。到此,環境的bring up工作完美收工。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM