KafKa集群搭建&常用命令

1、KafKa概述

1.1 定义

KafKa是一个分布式的基于发布/订阅模式的消息队列,主要应用于大数据试试处理领域

是一个分布式、支持分区的(partition)、多副本的(replica),基于zookeeper协调的分布式消息系统,它的最大的特性就是可以实时的处理大量数据以满足各种需求场景:比如基于hadoop的批处理系统、低延迟的实时系统、Storm/Spark流式处理引擎,web/nginx日志、访问日志,消息服务等等,用scala语言编写,Linkedin于2010年贡献给了Apache基金会并成为顶级开源项目。

名称 解释
Broker 消息中间件处理节点,一个Kafka节点就是一个broker,一个或者多个Broker可以组成一个Kafka集群
Topic Kafka根据topic对消息进行归类,发布到Kafka集群的每条消息都需要指定一个topic
Producer 消息生产者,向Broker发送消息的客户端
Consumer 消息消费者,从Broker读取消息的客户端
ConsumerGroup 每个Consumer属于一个特定的Consumer Group,一条消息可以被多个不同的Consumer Group消费,但是一个Consumer Group中只能有一个Consumer能够消费该消息
Partition 物理上的概念,一个topic可以分为多个partition,每个partition内部消息是有序的

2 kafka&zookeper配置和启动

kafka在??版本之后内部自带了zk, 当然也可一自己来安装zk。本次我么使用的是自带zk的kafka来测试的

2.1 kafka安装

1. 安装jdk
2. 下载kafka安装包

2.2 kafka&zookeeper配置

2.2.1 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.

#
# This configuration file is intended for use in ZK-based mode, where Apache ZooKeeper is required.
# 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  # 每个kafka服务器是一个broker,如果kafka存在集群则...???

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

# The address the socket server listens on. If not configured, the host name will be equal to the value of
# java.net.InetAddress.getCanonicalHostName(), with PLAINTEXT listener name, and port 9092.
#   FORMAT:
#     listeners = listener_name://host_name:port
#   EXAMPLE:
#     listeners = PLAINTEXT://your.host.name:9092
listeners=PLAINTEXT://192.168.190.136:9092  # 这里用来配置kafka的监听端口

# Listener name, hostname and port the broker will advertise to clients.
# If not set, it uses the value for "listeners".
#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 separated list of directories under which to store log files
log.dirs=/opt/kafka/kafka-logs

# 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 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 excessive 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=localhost:2181  # 这里用于配置zookeeper的地址和端口, 如果存在zk集群,则填写集群的多个ip:port

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


############################# 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

2.2.2 zookeeper.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.
# the directory where the snapshot is stored.
dataDir=/opt/kafka/kafka_2.12-3.5.0/zookeeper/data
dataLogDir=/opt/kafka/kafka_2.12-3.5.0/zookeeper/log
# the port at which the clients will connect
clientPort=2181
# disable the per-ip limit on the number of connections since this is a non-production config
maxClientCnxns=0
# Disable the adminserver by default to avoid port conflicts.
# Set the port to something non-conflicting if choosing to enable this
admin.enableServer=false
# admin.serverPort=8080

#设置连接参数,添加如下配置
#为zk的基本时间单元,毫秒
tickTime=2000
#Leader-Follower初始通信时限 tickTime*10
initLimit=10
#Leader-Follower同步通信时限 tickTime*5
syncLimit=5

# #设置broker Id的服务地址
server.0=192.168.190.136:2888:3888

2.3 kafka&zookeeper的启动与

# 注意要先启动zookeeper再启动kafka

# 启动zookeeper
./zookeeper-server-start.sh -daemon ../config/zookeeper.properties

# 启动kafka
./kafka-server-start.sh -daemon ../config/server.properties


# 停止zookeeper
./zookeeper-server-stop.sh

# 停止kafka
./kafka-server-stop.sh

3 kafka相关操作命令

3.1 创建kafka的topic

./kafka-topics.sh --create --bootstrap-server 192.168.190.136:9092 --replication-factor 1 --partitions 1 --topic test
# 1 说明:
# --bootstrap-server 192.168.190.136:9092 表示kafka地址和端口
#--zookeeper:定义 zookeeper 集群服务器地址,如果有多个 IP 地址使用逗号分割,一般使用一个 IP 即可/ 2.20废弃!!!!!!!!!!!!!
#--replication-factor:定义分区副本数,1 代表单副本,建议为 2 
#--partitions:定义分区数 
#--topic:定义 topic 名称

3.2 查看topic信息

./kafka-topics.sh --list --bootstrap-server 192.168.190.136:9092
# 2 说明:
	--bootstrap-server 192.168.190.136:9092 表示kafka地址和端口

3.3 创建kafka生产者

kafka自带了一个producer的命令客户端,可以从本地文件中读取内容,或者我们也可以一命令行中直接输入内容,并将这些内容以消息的形式送到kafka集群中。在默认情况下,没一行会被当成一个独立的消息。使用kafka的发送消息的客户端,指定发送到kafka服务器地址和topic

# 创建一个kafka控制台的生产者,创建后可在控制台直接输入信息发送到对应的topic下
./kafka-console-producer.sh --broker-list 192.168.190.136:9092 --topic test

3.4 创建kafka消费者

# 创建一个kafka控制台的消费者,创建后可直接取对应的topic的数据并输出
./kafka-console-consumer.sh --bootstrap-server 192.168.190.136:9092 --topic test --from-beginning

#--from-beginning:会把主题中以往所有的数据都读取出来

3.5 查看消费者组列表

./kafka-consumer-groups.sh --bootstrap-server 192.168.190.136:9092 --list

3.6 查看kafka中某一个消费者组的消费情况

./kafka-consumer-groups.sh --bootstrap-server 192.168.190.136:9092 --group console-consumer-6920 --describe

# console-consumer-6920: 表示消费者组
# 返回如下
GROUP TOPIC PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG  CONSUMER-ID HOST  CLIENT-ID
console-consumer-6920 test      0          -               12              -               console-consumer-e162ef6d-600f-45d1-8198-af7e230642a7 /192.168.190.136 console-consumer

4 zookeeper相关命令

4.1 连接zookeeper

# ./zookeeper-shell.sh zookeeper_server:port --> 连接zookeeper
./zookeeper-shell.sh 192.168.190.136:2181

# 不进入zookeeper执行相关指令
./zookeeper-shell.sh 192.168.190.136:2181 ls /                  # 查看当前 ZooKeeper 中所包含的内容
./zookeeper-shell.sh 192.168.190.136:2181 ls -s /			   # 查看当前节点数据
./zookeeper-shell.sh 192.168.190.136:2181 ls /brokers/ids       # 
./zookeeper-shell.sh 192.168.190.136:2181 ls /brokers/topics
./zookeeper-shell.sh 192.168.190.136:2181 get /brokers/ids/0

4.2 查看当前Zookeeper中所含的内容

# 查看当前Zookeeper中所含的内容
ls /

4.3 查看当前节点数据

ls -s /
# 返回如下
[admin, brokers, cluster, config, consumers, controller, controller_epoch, feature, isr_change_notification, latest_producer_id_block, log_dir_event_notification, zookeeper]
cZxid = 0x0                               # 数据节点创建时的事务 ID
ctime = Wed Dec 31 16:00:00 PST 1969 	  # 数据节点创建时的时间
mZxid = 0x0 							# 数据节点最后一次更新时的事务 ID
mtime = Wed Dec 31 16:00:00 PST 1969 	  # 数据节点最后一次更新时的时间
pZxid = 0x200000057                       # 数据节点的子节点最后一次被修改时的事务 ID
cversion = 18						    # 子节点的更改次数
dataVersion = 0						    # 节点数据的更改次数
aclVersion = 0                            # 节点的 ACL 的更改次数
ephemeralOwner = 0x0                      # 如果节点是临时节点,则表示创建该节点的会话的 SessionID;如果节点是持久节点,则该属性值为 0
dataLength = 0                            # 数据内容的长度
numChildren = 12                          # 数据节点当前的子节点个数

4.4 创建节点

#创建序列化永久节点:
create -s /testnode test
#创建临时节点
create -e /testnode-temp testtemp
#创建永久节点:
create /testnode-p testp

4.5 获取节点

ls path [watch]
get path [watch]
ls -s path [watch]

4.6 修改节点

ls -s /
get -s /testnode-temp
set /testnode-temp 123
get -s /testnode-temp

4.7 监听节点

get /testnode-temp watch
set  /testnode-temp testwatch
#他会回调Watch得到触发结果

4.8 删除节点

#普通删除的命令
delete path [version]
#递归删除的命令
rmr path [version]

5 知识点

5.1 单播消息

在一个kafka的topic中,启动两个消费者,一个生产者。当生产者发送消息,这条消息是否同时被这两个消费者消费?

如果多个消费者在同一个消费组,那么只有一个消费者可以收到订阅的topic中的消息。换言之,同一个消费者组中只能有一个消费者收到一个topic中的消息。

5.2多播消息

不同的消费组订阅同一个topic,

5.3 主题和分区

5.3.1 主题Topic

​ 主题Topic可以理解成一个类别的名称。 kafka通过Topic将消息进行分类。不同的topic挥别订阅该topic的消费者消费。

​ 但是如果这个topic中的消息非常多,多到需要几个T的大小占用磁盘空间(消息是被保存到log日志文件中)。由此为了解决文件过大的问题,kafka提出鹅Partition分区的概念。

5.3.2 分区partition

partition_01

你可能感兴趣的:(mq消息中间件,kafka,分布式)