kafka原理及常用命令

一、kafka命令

1)进入kafka pod

kubectl exec -it kafka-deployment-d8cb6bb7d-kwkv7 /bin/bash
  1. cd 到opt/kafka/bin目录(不进入也可以)

1.1 修改config参数

查看所有参数:cat /opt/kafka/config/server.properties

bash-4.4#  cat /opt/kafka/config/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.
broker.id=-1

############################# 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 separated list of directories under which to store log files
log.dirs=/kafka/kafka-logs-kafka-hostname

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

# 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=kafka-zookeeper-service.paas-basic: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
replica.fetch.max.bytes=1073741824
advertised.port=30092
advertised.host.name=192.168.180.37
manage.port=tcp://10.96.85.80:9000
service.service.port=9092
manage.service.host=10.96.85.80
zookeeper.service.service.port=2181
service.port.9092.tcp.addr=10.109.71.106
manage.port.9000.tcp.proto=tcp
batch.size=4096
message.max.bytes=1073741824
zookeeper.service.port.2181.tcp.addr=10.99.148.125
service.service.host=10.109.71.106
port=9092
service.port.9092.tcp.proto=tcp
zookeeper.service.port.2181.tcp.proto=tcp
auto.create.topics.enable=true
zookeeper.service.port.2181.tcp.port=2181
zookeeper.service.service.host=10.99.148.125
service.port=tcp://10.109.71.106:9092
manage.port.9000.tcp=tcp://10.96.85.80:9000
manage.port.9000.tcp.port=9000
service.port.9092.tcp.port=9092
zookeeper.service.port=tcp://10.99.148.125:2181
manage.service.port.manage=9000
manage.service.port=9000
service.service.port.kafka=9092
zookeeper.service.port.2181.tcp=tcp://10.99.148.125:2181
manage.port.9000.tcp.addr=10.96.85.80
zookeeper.service.service.port.zookeeper=2181
service.port.9092.tcp=tcp://10.109.71.106:9092
bash-4.4# 
# 修改为12小时  12*3600*1000=43200000
kafka-configs.sh --zookeeper kafka-zookeeper-service.paas-basic:2181 --entity-type topics --entity-name cdc_ticdc_total_topic --alter --add-config retention.ms=43200000
# 查看是否改成功
bash-4.4# kafka-configs.sh --zookeeper kafka-zookeeper-service.paas-basic:2181 --describe --entity-type topics --entity-name cdc_ticdc_total_topic 
Configs for topic 'cdc_ticdc_total_topic' are retention.ms=43200000

1.2 用以下命令测试

查看已创建的所有topic

kafka-topics.sh --zookeeper 192.168.180.8:2181 --list 

创建topic

#新创建一个topic, partitions表示分区数,replication-factor表示该topic需要在不同的broker中保存几份,不能超过kafka的broker数,单机只能为1
bash-4.4# kafka-topics.sh -topic test2 -create -partitions 5 -replication-factor 3 -zookeeper 192.168.180.8:2181
Created topic test2.
bash-4.4#

查看某个指定topic属性

bash-4.4# kafka-topics.sh -describe -zookeeper 192.168.180.8:2181 -topic test2
Topic:test2     PartitionCount:5        ReplicationFactor:3     Configs:
        Topic: test2    Partition: 0    Leader: 1003    Replicas: 1003,1002,1001        Isr: 1003,1002,1001
        Topic: test2    Partition: 1    Leader: 1001    Replicas: 1001,1003,1002        Isr: 1001,1003,1002
        Topic: test2    Partition: 2    Leader: 1002    Replicas: 1002,1001,1003        Isr: 1002,1001,1003
        Topic: test2    Partition: 3    Leader: 1003    Replicas: 1003,1001,1002        Isr: 1003,1001,1002
        Topic: test2    Partition: 4    Leader: 1001    Replicas: 1001,1002,1003        Isr: 1001,1002,1003

修改Topic

#可以增加分片的数量,不能减少分片的数量,不支持副本的修改。
bash-4.4# kafka-topics.sh -topic test1 -create -partitions 3 -replication-factor 3 -zookeeper 192.168.180.8:2181
Created topic test1.

bash-4.4# kafka-topics.sh -describe -zookeeper 192.168.180.8:2181 -topic test1
Topic:test1     PartitionCount:3        ReplicationFactor:3     Configs:
        Topic: test1    Partition: 0    Leader: 1003    Replicas: 1003,1002,1001        Isr: 1003,1002,1001
        Topic: test1    Partition: 1    Leader: 1001    Replicas: 1001,1003,1002        Isr: 1001,1003,1002
        Topic: test1    Partition: 2    Leader: 1002    Replicas: 1002,1001,1003        Isr: 1002,1001,1003
        
bash-4.4# kafka-topics.sh --alter --zookeeper 192.168.180.8:2181 --topic test1 --partitions 6
WARNING: If partitions are increased for a topic that has a key, the partition logic or ordering of the messages will be affected
Adding partitions succeeded!

bash-4.4# kafka-topics.sh -describe -zookeeper 192.168.180.8:2181 -topic test1
Topic:test1     PartitionCount:6        ReplicationFactor:3     Configs:
        Topic: test1    Partition: 0    Leader: 1003    Replicas: 1003,1002,1001        Isr: 1003,1002,1001
        Topic: test1    Partition: 1    Leader: 1001    Replicas: 1001,1003,1002        Isr: 1001,1003,1002
        Topic: test1    Partition: 2    Leader: 1002    Replicas: 1002,1001,1003        Isr: 1002,1001,1003
        Topic: test1    Partition: 3    Leader: 1003    Replicas: 1003,1002,1001        Isr: 1003,1002,1001
        Topic: test1    Partition: 4    Leader: 1001    Replicas: 1001,1003,1002        Isr: 1001,1003,1002
        Topic: test1    Partition: 5    Leader: 1002    Replicas: 1002,1001,1003        Isr: 1002,1001,1003

删除Topic

bash-4.4# kafka-topics.sh --delete --zookeeper 192.168.180.8:2181 --topic aaaa
Topic aaaa is marked for deletion.
Note: This will have no impact if delete.topic.enable is not set to true.

创建生产者

#新建连接
kafka-console-producer.sh -broker-list localhost:9092 -topic test2

创建消费者组

作为消费者组g111,另开一个终端窗口执行如下命令

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test2 --group g111 --from-beginning

作为消费者组g111,再另开一个终端窗口执行如下命令

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test2 --group g111 --from-beginning

作为消费者组g222,再另开一个终端窗口执行如下命令

kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test2 --group g222 --from-beginning

在生产端输入字符串后,两个消费者组能接收到对应的字符串,g111两个消费者接收的字符串不重复。

查看所有topic的消费者组

bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list
g111
g222

删除消费者组

bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --delete --group g111--from-beginning
Deletion of requested consumer groups ('g111--from-beginning') was successful.

查看某个消费者组的情况

bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group g111

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST            CLIENT-ID
g111            test1           3          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test1           0          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test1           4          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test1           1          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test1           5          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test1           2          0               0               0               consumer-1-f45947b2-dc84-4dac-bda0-dfc90968944c /172.26.0.1     consumer-1
g111            test2           0          3               3               0               consumer-1-5924ca97-fdd4-4a4a-ac51-f648295579ca /172.26.0.1     consumer-1
g111            test2           1          3               3               0               consumer-1-5924ca97-fdd4-4a4a-ac51-f648295579ca /172.26.0.1     consumer-1
g111            test2           4          2               2               0               consumer-1-e752db05-1b18-458c-b03f-51ab4700c048 /172.26.0.1     consumer-1
g111            test2           2          3               3               0               consumer-1-8547a1f2-dd7c-4f60-bb6e-964e69e4717f /172.26.0.1     consumer-1
g111            test2           3          3               3               0               consumer-1-c6f327d1-361f-473c-8fed-b403154d57e4 /172.26.0.1     consumer-1

查看某个topic每个分区的最小值

bash-4.4# kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092 --topic test2 --time -2
test2:0:0
test2:1:0
test2:2:0
test2:3:0
test2:4:0

查看某个topic每个分区的最大值

bash-4.4# kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092 --topic test2 --time -1
test2:0:2
test2:1:3
test2:2:2
test2:3:2
test2:4:2

更新某个消费者组(所有消费者组)的某个topic(所有topic)的消息移到指定位置(以下类似这四个命令都可以用,没有一个个试)

#把某个消费者组的某个topic的消息移到指定位置(to-offset后面的数字代表前面查到的最小值到最大值范围中的数据)
bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --to-offset 2 --topic test2 --execute
GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          2
g222                           test2                          1          2
g222                           test2                          2          2
g222                           test2                          3          2
g222                           test2                          0          2


#把所有消费者组(--all-groups)的某个topic的消息移到指定位置(to-offset后面的数字代表前面查到的最小值到最大值范围中的数据)
bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --all-groups --reset-offsets --to-offset 2 --topic test2 --execute

Error: Assignments can only be reset if the group 'g111' is inactive, but the current state is Stable.
GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          2
g222                           test2                          1          2
g222                           test2                          2          2
g222                           test2                          3          2
g222                           test2                          0          2
g222--from-beginning           test2                          4          2
g222--from-beginning           test2                          1          2
g222--from-beginning           test2                          2          2
g222--from-beginning           test2                          3          2
g222--from-beginning           test2                          0          2
g111--from-beginning           test2                          4          2
g111--from-beginning           test2                          1          2
g111--from-beginning           test2                          2          2
g111--from-beginning           test2                          3          2
g111--from-beginning           test2                          0          2

#把某个消费者组的所有topic(--all-topics)的消息移到指定位置(to-offset后面的数字代表前面查到的最小值到最大值范围中的数据)
bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --to-offset 2 --all-topics --execute
GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          2
g222                           test2                          1          2
g222                           test2                          2          2
g222                           test2                          3          2
g222                           test2                          0          2

#把所有消费者组(--all-groups)的所有topic(--all-topics)的消息移到指定位置(to-offset后面的数字代表前面查到的最小值到最大值范围中的数据)
bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --all-groups  --reset-offsets --to-offset 2 --all-topics --execute
Error: Assignments can only be reset if the group 'g111' is inactive, but the current state is Stable.
GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          2
g222                           test2                          1          2
g222                           test2                          2          2
g222                           test2                          3          2
g222                           test2                          0          2
g222--from-beginning           test2                          4          2
g222--from-beginning           test2                          1          2
g222--from-beginning           test2                          2          2
g222--from-beginning           test2                          3          2
g222--from-beginning           test2                          0          2
g111--from-beginning           test2                          4          2
g111--from-beginning           test2                          1          2
g111--from-beginning           test2                          2          2
g111--from-beginning           test2                          3          2
g111--from-beginning           test2                          0          2

更新某个消费者组(所有消费者组)的某个topic(所有topic)重置到最早位置消费

#将某个消费者组的某个topic重置到最早位置消费
bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --to-earliest --topic test2 --execute

GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          0
g222                           test2                          1          0
g222                           test2                          2          0
g222                           test2                          3          0
g222                           test2                          0          0

更新某个消费者组(所有消费者组)的某个topic(所有topic)到当前最新位移

bash-4.4# kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --topic test2 --to-latest --execute

GROUP                          TOPIC                          PARTITION  NEW-OFFSET
g222                           test2                          4          2
g222                           test2                          1          3
g222                           test2                          2          3
g222                           test2                          3          3
g222                           test2                          0          3

更新某个消费者组(所有消费者组)的某个topic(所有topic)到指定时刻开始(未验证)

kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --topic test2 --to-datetime 2021-10-25T12:30:00.000

更新某个消费者组(所有消费者组)的某个topic(所有topic)到当前位置(未验证)

kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group g222 --reset-offsets --topic test2 --to-current --execute

二、kafka原理

2.1 消息队列通信的模式

通过上面的例子我们引出了消息中间件,并且介绍了消息队列出现后的好处,这里就需要介绍消息队列通信的两种模式了:

一、 点对点模式
 在这里插入图片描述
 如上图所示,点对点模式通常是基于拉取或者轮询的消息传送模型,这个模型的特点是发送到队列的消息被一个且只有一个消费者进行处理。生产者将消息放入消息队列后,由消费者主动的去拉取消息进行消费。点对点模型的的优点是消费者拉取消息的频率可以由自己控制。但是消息队列是否有消息需要消费,在消费者端无法感知,所以在消费者端需要额外的线程去监控。

二、 发布订阅模式
  在这里插入图片描述
  如上图所示,发布订阅模式是一个基于消息送的消息传送模型,改模型可以有多种不同的订阅者。生产者将消息放入消息队列后,队列会将消息推送给订阅过该类消息的消费者(类似微信公众号)。由于是消费者被动接收推送,所以无需感知消息队列是否有待消费的消息!但是consumer1、consumer2、consumer3由于机器性能不一样,所以处理消息的能力也会不一样,但消息队列却无法感知消费者消费的速度!所以推送的速度成了发布订阅模模式的一个问题!假设三个消费者处理速度分别是8M/s、5M/s、2M/s,如果队列推送的速度为5M/s,则consumer3无法承受!如果队列推送的速度为2M/s,则consumer1、consumer2会出现资源的极大浪费!

2.2 Kafka

基础架构及术语
  话不多说,先看图,通过这张图我们来捋一捋相关的概念及之间的关系:
在这里插入图片描述
Producer:Producer即生产者,消息的产生者,是消息的入口。

kafka cluster:

  1. Broker:Broker是kafka实例,每个服务器上有一个或多个kafka的实例,我们姑且认为每个broker对应一台服务器。每个kafka集群内的broker都有一个不重复的编号,如图中的broker-0、broker-1等……

  2. Topic:消息的主题,可以理解为消息的分类,kafka的数据就保存在topic。在每个broker上都可以创建多个topic。

  3. Partition:Topic的分区,每个topic可以有多个分区,分区的作用是做负载,提高kafka的吞吐量。同一个topic在不同的分区的数据是不重复的,partition的表现形式就是一个一个的文件夹!

  4. Replication:每一个分区都有多个副本,副本的作用是做备胎。当主分区(Leader)故障的时候会选择一个备胎(Follower)上位,成为Leader。在kafka中默认副本的最大数量是10个,且副本的数量不能大于Broker的数量,follower和leader绝对是在不同的机器,同一机器对同一个分区也只可能存放一个副本(包括自己)。

  5. Message:每一条发送的消息主体。

Consumer:消费者,即消息的消费方,是消息的出口。

Consumer Group:我们可以将多个消费组组成一个消费者组,在kafka的设计中同一个分区的数据只能被消费者组中的某一个消费者消费。同一个消费者组的消费者可以消费同一个topic的不同分区的数据,这也是为了提高kafka的吞吐量!

Zookeeper:kafka集群依赖zookeeper来保存集群的的元信息,来保证系统的可用性。

2.3 工作流程分析

上面介绍了kafka的基础架构及基本概念,不知道大家看完有没有对kafka有个大致印象,如果对还比较懵也没关系!我们接下来再结合上面的结构图分析kafka的工作流程,最后再回来整个梳理一遍。

发送数据

我们看上面的架构图中,producer就是生产者,是数据的入口。注意看图中的红色箭头,Producer在写入数据的时候永远的找leader,不会直接将数据写入follower!那leader怎么找呢?写入的流程又是什么样的呢?我们看下图:
在这里插入图片描述
  发送的流程就在图中已经说明了,需要注意的一点是,消息写入leader后,follower是主动的去leader进行同步的!producer采用push模式将数据发布到broker,每条消息追加到分区中,顺序写入磁盘,所以保证同一分区内的数据是有序的!写入示意图如下:
在这里插入图片描述
  上面说到数据会写入到不同的分区,那kafka为什么要做分区呢?分区的主要目的是:
  1、 方便扩展。因为一个topic可以有多个partition,所以可以通过扩展机器应对日益增长的数据量。
  2、 提高并发。以partition为读写单位,可以多个消费者同时消费数据,提高了消息的处理效率。
  
  熟悉负载均衡的朋友应该知道,当我们向某个服务器发送请求的时候,服务端可能会对请求做一个负载,将流量分发到不同的服务器,那在kafka中,如果某个topic有多个partition,producer又怎么知道该将数据发往哪个partition呢?kafka中有几个原则:
  1、 partition在写入的时候可以指定需要写入的partition,如果有指定,则写入对应的partition。
  2、 如果没有指定partition,但是设置了数据的key,则会根据key的值hash出一个partition。
  3、 如果既没指定partition,又没有设置key,则会轮询选出一个partition。

保证消息不丢失是一个消息队列中间件的基本保证,上面的写入流程图中有描述出来,那就是通过ACK应答机制!在生产者向队列写入数据的时候可以设置参数来确定是否确认kafka接收到数据,这个参数可设置的值为0、1、all。
  0代表producer往集群发送数据不需要集群的返回,不确保消息发送成功。安全性最低但效率最高。
  1代表producer往集群发送数据只要leader应答就可以发送下一条,只确保leader发送成功。
  all代表producer往集群发送数据需要所有的follower都完成从leader的同步才会发送下一条,确保leader发送成功和所有的副本都完成备份。安全性最高,但是效率最低。

最后要注意的是,如果往不存在的topic写数据,能不能写入成功呢?kafka会自动创建topic,分区和副本的数量根据默认配置都是1。

保存数据

Producer将数据写入kafka后,集群就需要对数据进行保存了!kafka将数据保存在磁盘,可能在我们的一般的认知里,写入磁盘是比较耗时的操作,不适合这种高并发的组件。Kafka初始会单独开辟一块磁盘空间,顺序写入数据(效率比随机写入高)。

Partition 结构
  每个topic都可以分为一个或多个partition,如果你觉得topic比较抽象,那partition就是比较具体的东西了!Partition在服务器上的表现形式就是一个一个的文件夹,每个partition的文件夹下面会有多组segment文件,每组segment文件又包含.index文件、.log文件、.timeindex文件(早期版本中没有)三个文件, log文件就实际是存储message的地方,而index和timeindex文件为索引文件,用于检索消息。
在这里插入图片描述
  如上图,这个partition有三组segment文件,每个log文件的大小是一样的,但是存储的message数量是不一定相等的(每条的message大小不一致)。文件的命名是以该segment最小offset来命名的,如000.index存储offset为0~368795的消息,kafka就是利用分段+索引的方式来解决查找效率的问题。

Message结构
上面说到log文件就实际是存储message的地方,我们在producer往kafka写入的也是一条一条的message,那存储在log中的message是什么样子的呢?消息主要包含消息体、消息大小、offset、压缩类型……等等!我们重点需要知道的是下面三个:
  1、 offset:offset是一个占8byte的有序id号,它可以唯一确定每条消息在parition内的位置!
  2、 消息大小:消息大小占用4byte,用于描述消息的大小。
  3、 消息体:消息体存放的是实际的消息数据(被压缩过),占用的空间根据具体的消息而不一样。

存储策略
  无论消息是否被消费,kafka都会保存所有的消息。那对于旧数据有什么删除策略呢?
  1、 基于时间,默认配置是168小时(7天)。
  2、 基于大小,默认配置是1073741824。
  需要注意的是,kafka读取特定消息的时间复杂度是O(1),所以这里删除过期的文件并不会提高kafka的性能!

消费数据

消息存储在log文件后,消费者就可以进行消费了。与生产消息相同的是,消费者在拉取消息的时候也是找leader去拉取。
  多个消费者可以组成一个消费者组(consumer group),每个消费者组都有一个组id!同一个消费组者的消费者可以消费同一topic下不同分区的数据,但是不会组内多个消费者消费同一分区的数据!!!是不是有点绕。我们看下图:
在这里插入图片描述
  图示是消费者组内的消费者小于partition数量的情况,所以会出现某个消费者消费多个partition数据的情况,消费的速度也就不及只处理一个partition的消费者的处理速度!如果是消费者组的消费者多于partition的数量,那会不会出现多个消费者消费同一个partition的数据呢?上面已经提到过不会出现这种情况!多出来的消费者不消费任何partition的数据。所以在实际的应用中,建议消费者组的consumer的数量与partition的数量一致!
  在保存数据的小节里面,我们聊到了partition划分为多组segment,每个segment又包含.log、.index、.timeindex文件,存放的每条message包含offset、消息大小、消息体……我们多次提到segment和offset,查找消息的时候是怎么利用segment+offset配合查找的呢?假如现在需要查找一个offset为368801的message是什么样的过程呢?我们先看看下面的图:
在这里插入图片描述
  1、 先找到offset的368801message所在的segment文件(利用二分法查找),这里找到的就是在第二个segment文件。
  2、 打开找到的segment中的.index文件(也就是368796.index文件,该文件起始偏移量为368796+1,我们要查找的offset为368801的message在该index内的偏移量为368796+5=368801,所以这里要查找的相对offset为5)。由于该文件采用的是稀疏索引的方式存储着相对offset及对应message物理偏移量的关系,所以直接找相对offset为5的索引找不到,这里同样利用二分法查找相对offset小于或者等于指定的相对offset的索引条目中最大的那个相对offset,所以找到的是相对offset为4的这个索引。
  3、 根据找到的相对offset为4的索引确定message存储的物理偏移位置为256。打开数据文件,从位置为256的那个地方开始顺序扫描直到找到offset为368801的那条Message。

这套机制是建立在offset为有序的基础上,利用segment+有序offset+稀疏索引+二分查找+顺序查找等多种手段来高效的查找数据!至此,消费者就能拿到需要处理的数据进行处理了。那每个消费者又是怎么记录自己消费的位置呢?在早期的版本中,消费者将消费到的offset维护zookeeper中,consumer每间隔一段时间上报一次,这里容易导致重复消费,且性能不好!在新的版本中消费者消费到的offset已经直接维护在kafk集群的__consumer_offsets这个topic中!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值