Kafka快速实战与基本原理详解

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

Kafka的使用场景

  • 日志收集:一个公司可以用Kafka收集各种服务的log,通过kafka以统一接口服务的方式开放给各种consumer,例如hadoop、Hbase、Solr等。
  • 消息系统:解耦和生产者和消费者、缓存消息等。
  • 用户活动跟踪:Kafka经常被用来记录web用户或者app用户的各种活动,如浏览网页、搜索、点击等活动,这些活动信息被各个服务器发布到kafka的topic中,然后订阅者通过订阅这些topic来做实时的监控分析,或者装载到hadoop、数据仓库中做离线分析和挖掘。
  • 运营指标:Kafka也经常用来记录运营监控数据。包括收集各种分布式应用的数据,生产各种操作的集中反馈,比如报警和报告。
1、Kafka基本概念

kafka是一个分布式的,分区的消息(官方称之为commit log)服务。它提供一个消息系统应该具备的功能,但是确有着独特的设计。可以这样来说,Kafka借鉴了JMS规范的思想,但是确并没有完全遵循JMS规范。

首先,让我们来看一下基础的消息(Message)相关术语:

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

因此,从一个较高的层面上来看,producer通过网络发送消息到Kafka集群,然后consumer来进行消费,如下图:

在这里插入图片描述
服务端(brokers)和客户端(producer、consumer)之间通信通过TCP协议来完成。
注意:一个broker只能被一个consumer消费

2、kafka的基本使用

安装前的环境准备

由于Kafka是用Scala语言开发的,运行在JVM上,因此在安装Kafka之前需要先安装JDK。

yum install java-1.8.0-openjdk* -y

kafka依赖zookeeper,所以需要先安装zookeeper

wget https://archive.apache.org/dist/zookeeper/zookeeper-3.5.8/apache-zookeeper-3.5.8-bin.tar.gz
tar -zxf apache-zookeeper-3.5.8-bin.tar.gz
cd  apache-zookeeper-3.5.8-bin
cp conf/zoo_sample.cfg conf/zoo.cfg

启动zookeeper

bin/zkServer.sh start
bin/zkCli.sh 
ls /			#查看zk的根目录相关节点

第一步:下载安装包

下载3.1.0 release版本,并解压:

wget https://archive.apache.org/dist/kafka/3.1.0/kafka_2.13-3.1.0.tgz  # 2.13是scala的版本,3.1.0是kafka的版本
tar -xzf kafka_2.13-3.1.0.tgz
cd kafka_kafka_2.13-3.1.0

第二步:修改配置

修改配置文件config/server.properties:

#broker.id属性在kafka集群中必须要是唯一
broker.id=0
#kafka部署的机器ip和提供服务的端口号
listeners=PLAINTEXT://192.168.65.60:9092   
#kafka的消息存储文件
log.dir=/usr/local/data/kafka-logs
#kafka连接zookeeper的地址
zookeeper.connect=192.168.65.60:2181

第三步:启动服务

启动脚本语法:kafka-server-start.sh [-daemon] server.properties,如下

可以看到,server.properties的配置路径是一个强制的参数,-daemon表示以后台进程运行,否则ssh客户端退出后,就会停止服务。(注意,在启动kafka时会使用linux主机名关联的ip地址,所以需要把主机名和linux的ip映射配置到本地host里,用vim /etc/hosts)

# 启动kafka,运行日志在logs目录的server.log文件里
sh bin/kafka-server-start.sh -daemon config/server.properties   #后台启动,不会打印日志到控制台

# 我们进入zookeeper目录通过zookeeper客户端查看下zookeeper的目录树
bin/zkCli.sh 
ls /		#查看zk的根目录kafka相关节点
ls /brokers/ids	#查看kafka节点

# 停止kafka
bin/kafka-server-stop.sh
3、server.properties核心配置详解:
############################# Server Basics #############################

# 每个broker都可以用一个唯一的非负整数id进行标识;这个id可以作为broker的“名字”,
# 你可以选择任意你喜欢的数字作为id,只要id是唯一的即可。
broker.id=0

############################# Socket Server Settings #############################
# server接受客户端连接的端口,ip配置kafka本机ip即可
listeners=PLAINTEXT://192.168.93.230: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 #############################

# kafka存放数据的路径。这个路径并不是唯一的,可以是多个,路径之间只需要使用逗号分隔即可;
# 每当创建新partition时,都会选择在包含最少partitions的路径下进行。
log.dirs=/usr/kafka-logs

# 创建topic的默认分区数
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 #############################

# 每个日志文件删除之前保存的时间。默认数据保存时间对所有topic都一样。
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连接字符串的格式为:hostname:port,此处hostname和port分别是ZooKeeper集群中某个节点的host和port;
# zookeeper如果是集群,连接方式为 hostname1:port1, hostname2:port2, hostname3:port3
zookeeper.connect=192.168.93.230:2181

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

4、创建主题

现在我们来创建一个名字为“test”的Topic,这个topic只有一个分区partition,并且备份因子也设置为1:

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --create --bootstrap-server 192.168.93.230:9092 --replication-factor 1 --partitions 1 --topic test
Created topic test.

现在我们可以通过以下命令来查看kafka中目前存在的topic

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --list --bootstrap-server 192.168.93.230:9092
test
topic01
topic02
topic03

除了我们通过手工的方式创建Topic,当producer发布一个消息到某个指定的Topic,这个Topic如果不存在,就自动创建。

删除主题

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --delete --topic test --bootstrap-server 192.168.93.230:9092
[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --list --bootstrap-server 192.168.93.230:9092
topic01
topic02
topic03
5、生产消息

kafka自带了一个producer命令客户端,可以从本地文件中读取内容,或者我们也可以以命令行中直接输入内容,并将这些内容以消息的形式发送到kafka集群中。在默认情况下,每一个行会被当做成一个独立的消息。
首先我们要运行发布消息的脚本,然后在命令中输入要发送的消息的内容:

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-producer.sh --bootstrap-server 192.168.93.230:9092 --topic test 
>this is a msg
>this is a another msg 
6、消费消息

对于consumer,kafka同样也携带了一个命令行客户端,会将获取到内容在命令中进行输出,默认是消费最新的消息:

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-consumer.sh --bootstrap-server 192.168.93.230:9092 --topic test   

如果想要消费之前的消息可以通过–from-beginning参数指定,如下命令:

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-consumer.sh --bootstrap-server 192.168.93.230:9092 --from-beginning --topic test 

如果你是通过不同的终端窗口来运行以上的命令,你将会看到在producer终端输入的内容,很快就会在consumer的终端窗口上显示出来。
以上所有的命令都有一些附加的选项;当我们不携带任何参数运行命令的时候,将会显示出这个命令的详细用法。

消费多主题

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-consumer.sh --bootstrap-server 192.168.93.230:9092 --whitelist "test|clyu"

单播消费

一条消息只能被某一个消费者消费的模式,类似queue模式,只需让所有消费者在同一个消费组里即可
分别在两个客户端执行如下消费命令,然后往主题里发送消息,结果只有一个客户端能收到消息

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-consumer.sh --bootstrap-server 192.168.93.230:9092  --consumer-property group.id=testGroup --topic test

多播消费

一条消息能被多个消费者消费的模式,类似publish-subscribe模式费,针对Kafka同一条消息只能被同一个消费组下的某一个消费者消费的特性,要实现多播只要保证这些消费者属于不同的消费组即可。我们再增加一个消费者,该消费者属于testGroup-2消费组,结果两个客户端都能收到消息

[root@master kafka_2.13-3.1.0] sh bin/kafka-console-consumer.sh --bootstrap-server 192.168.93.230:9092 --consumer-property group.id=testGroup-2 --topic test 

查看消费组名

[root@master kafka_2.13-3.1.0] sh bin/kafka-consumer-groups.sh --bootstrap-server 192.168.93.230:9092 --list 

查看消费组的消费偏移量

[root@master kafka_2.13-3.1.0] sh bin/kafka-consumer-groups.sh --bootstrap-server 192.168.93.230:9092 --describe --group testGroup
GROUP                   TOPIC                     PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID     HOST            CLIENT-ID
group_id_sampling_month topic_name_sampling_month 0          2               2               0               -               -               -

current-offset:当前消费组的已消费偏移量
log-end-offset:主题对应分区消息的结束偏移量(HW)
lag:当前消费组未消费的消息数

7、主题Topic和消息日志Log

可以理解Topic是一个类别的名称,同类消息发送到同一个Topic下面。对于每一个Topic,下面可以有多个分区(Partition)日志文件:
在这里插入图片描述
Partition是一个有序的message序列,这些message按顺序添加到一个叫做commit log的文件中。每个partition中的消息都有一个唯一的编号,称之为offset,用来唯一标示某个分区中的message。

kafka一般不会删除消息,不管这些消息有没有被消费。只会根据配置的日志保留时间(log.retention.hours)确认消息多久被删除,默认保留最近一周的日志消息。kafka的性能与保留的消息数据量大小没有关系,因此保存大量的数据消息日志信息不会有什么影响。

每个consumer是基于自己在commit log中的消费进度(offset)来进行工作的。在kafka中,消费offset由consumer自己来维护;一般情况下我们按照顺序逐条消费commit log中的消息,当然我可以通过指定offset来重复消费某些消息,或者跳过某些消息。

这意味kafka中的consumer对集群的影响是非常小的,添加一个或者减少一个consumer,对于集群或者其他consumer来说,都是没有影响的,因为每个consumer维护各自的消费offset。

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --create --bootstrap-server 192.168.93.230:9092 --replication-factor 1 --partitions 2 --topic testclyu
Created topic testclyu.

replication-factor表示储存的份数,其值最小是1,最大是broke的数量。因为我们这边broke是1,所以replication-factor最大数为1

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --create --bootstrap-server 192.168.93.230:9092 --replication-factor 2 --partitions 2 --topic testclyu1
Error while executing topic command : Replication factor: 2 larger than available brokers: 1.
[2022-07-01 21:38:09,677] ERROR org.apache.kafka.common.errors.InvalidReplicationFactorException: Replication factor: 2 larger than available brokers: 1.
 (kafka.admin.TopicCommand$)
 
[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --create --bootstrap-server 192.168.93.230:9092 --replication-factor 0 --partitions 2 --topic testclyu1
Error while executing topic command : The replication factor must be between 1 and 32767 inclusive
[2022-07-01 21:38:26,176] ERROR java.lang.IllegalArgumentException: The replication factor must be between 1 and 32767 inclusive
	at kafka.admin.TopicCommand$TopicService.createTopic(TopicCommand.scala:224)
	at kafka.admin.TopicCommand$TopicService.createTopic(TopicCommand.scala:219)
	at kafka.admin.TopicCommand$.main(TopicCommand.scala:55)
	at kafka.admin.TopicCommand.main(TopicCommand.scala)
 (kafka.admin.TopicCommand$)

每个partition,都对应一个commit log文件。一个partition中的message的offset都是唯一的,但是不同的partition中的message的offset可能是相同的。

进入日志目录,出现如下文件
在这里插入图片描述
查看下topic的情况

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --describe --bootstrap-server 192.168.93.230:9092 --topic testclyu
Topic: testclyu	TopicId: hhdDrAcvQtyy07t-jCWOuQ	PartitionCount: 2	ReplicationFactor: 1	Configs: segment.bytes=1073741824
	Topic: testclyu	Partition: 0	Leader: 0	Replicas: 0	Isr: 0
	Topic: testclyu	Partition: 1	Leader: 0	Replicas: 0	Isr: 0

以下是输出内容的解释,第一行是所有分区的概要信息,之后的每一行表示每一个partition的信息。
leader节点负责给定partition的所有读写请求。
replicas 表示某个partition在哪几个broker上存在备份。不管这个几点是不是”leader“,甚至这个节点挂了,也会列出。
isr 是replicas的一个子集,它只列出当前还存活着的,并且已同步备份了该partition的节点。

之前设置了topic的partition数量为1,备份因子为1,因此显示就如上所示了。

可以进入kafka的数据文件存储目录查看test和test1主题的消息日志文件:

[root@master kafka-logs] ll testclyu-0
总用量 8
-rw-r--r-- 1 root root 10485760 71 21:03 00000000000000000000.index
-rw-r--r-- 1 root root        0 71 21:03 00000000000000000000.log
-rw-r--r-- 1 root root 10485756 71 21:03 00000000000000000000.timeindex
-rw-r--r-- 1 root root        8 71 21:03 leader-epoch-checkpoint
-rw-r--r-- 1 root root       43 71 21:03 partition.metadata

消息日志文件主要存放在分区文件夹里的以log结尾的日志文件里

当然我们也可以通过如下命令增加topic的分区数量(目前kafka不支持减少分区):

[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh -alter --partitions 3 --bootstrap-server 192.168.93.230:9092 --topic testclyu
[root@master kafka_2.13-3.1.0] sh bin/kafka-topics.sh --describe --bootstrap-server 192.168.93.230:9092 --topic testclyu
Topic: testclyu	TopicId: hhdDrAcvQtyy07t-jCWOuQ	PartitionCount: 3	ReplicationFactor: 1	Configs: segment.bytes=1073741824
	Topic: testclyu	Partition: 0	Leader: 0	Replicas: 0	Isr: 0
	Topic: testclyu	Partition: 1	Leader: 0	Replicas: 0	Isr: 0
	Topic: testclyu	Partition: 2	Leader: 0	Replicas: 0	Isr: 0

可以这么来理解Topic,Partition和Broker

一个topic,代表逻辑上的一个业务数据集,比如按数据库里不同表的数据操作消息区分放入不同topic,订单相关操作消息放入订单topic,用户相关操作消息放入用户topic,对于大型网站来说,后端数据都是海量的,订单消息很可能是非常巨量的,比如有几百个G甚至达到TB级别,如果把这么多数据都放在一台机器上可定会有容量限制问题,那么就可以在topic内部划分多个partition来分片存储数据,不同的partition可以位于不同的机器上,每台机器上都运行一个Kafka的进程Broker。

为什么要对Topic下数据进行分区存储?

1、commit log文件会受到所在机器的文件系统大小的限制,分区之后可以将不同的分区放在不同的机器上,相当于对数据做了分布式存储,理论上一个topic可以处理任意数量的数据。

2、为了提高并行度。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值