SHIHUC

好记性不如烂笔头,还可以分享给别人看看! 专注基础算法,互联网架构,人工智能领域的技术实现和应用。
posts - 165, comments - 61, trackbacks - 0, articles - 0
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

Kafka研究【一】:bring up环境

Posted on 2018-06-13 09:17 shihuc 阅读(...) 评论(...) 编辑 收藏

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工作完美收工。