Kafka攻略(入門篇)

一、環(huán)境搭建

kafka的搭建依賴zookeeper,所以我們先配置zookeeper

# 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=/home/mq/zkdata
# the port at which the clients will connect
clientPort=2181

server.1=172.18.182.32:2888:3888
server.2=172.18.182.33:2888:3888
server.3=172.18.182.31:2888:3888

zookeeper正常啟動后用zkServer.sh status查看狀態(tài)。
然后配置Kafka的server.properties文件.

############################# Server Basics #############################

# The id of the broker. This must be set to a unique integer for each broker.
broker.id=0
delete.topic.enable=true
############################# 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
advertised.listeners=PLAINTEXT://172.18.182.32:9092

port=9092
host.name=172.18.182.32

# 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=/tmp/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=172.18.182.32:2181,172.18.182.33:2181,172.18.182.31: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

/bin/kafka-server-start.sh -daemon kafka_2.12-2.4.0/config/server.properties

如果jps發(fā)現(xiàn)沒啟動,前臺啟動查看報錯日志,或者取kafka/logs里面查看.

二、常用命令

# 啟動kafka
bin/kafka-server-start.sh -daemon config/server.properties
# 創(chuàng)建一個topic
bin/kafka-topics.sh --create --bootstrap-server 172.18.182.32:2181,172.18.182.33:2181,172.18.182.31:2181 --replication-factor 2 --partitions 2 --topic queuing-user-create
# topic列表
bin/kafka-topics.sh --list --zookeeper 172.18.182.32:2181,172.18.182.33:2181,172.18.182.31:2181
# topic描述,如果加--topic則可以看某個topic
# PartitionCount:分區(qū)數(shù)量,ReplicationFactor:副本數(shù)量,Partition:分區(qū)編號,Leader:是否是負責讀寫的分區(qū),如果只有一個則為None,Replicas:這個分區(qū)的副本在哪些節(jié)點,Isr:數(shù)據(jù)已同步的節(jié)點。
bin/kafka-topics.sh --describe --zookeeper 172.18.182.32:2181,172.18.182.33:2181,172.18.182.31:2181
Topic: queuing-survey-answer-status     PartitionCount: 2   ReplicationFactor: 2    Configs: 
    Topic: queuing-survey-answer-status Partition: 0    Leader: 1   Replicas: 1,2   Isr: 1
    Topic: queuing-survey-answer-status Partition: 1    Leader: 0   Replicas: 2,0   Isr: 0
Topic: queuing-survey-anwser    PartitionCount: 1   ReplicationFactor: 1    Configs: 
    Topic: queuing-survey-anwser    Partition: 0    Leader: none    Replicas: 2 Isr: 2
# 開啟一個調(diào)試生產(chǎn)者
bin/kafka-console-producer.sh --broker-list 172.18.182.32:2181,172.18.182.33:2181,172.18.182.31:2181 --topic queuing-survey-anwser
# 開啟一個調(diào)試消費者,也可以9092
bin/kafka-console-consumer.sh --bootstrap-server 172.18.182.32:2181,172.18.182.33:2181,172.18.182.31:2181  --topic queuing-user-create --from-beginning
# 日志查看
bin/kafka-run-class.sh kafka.tools.DumpLogSegments --files /tmp/kafka-logs/queuing-survey-answer-status-1/00000000000000000000.log --print-data-log
# 消費組查看
bin/kafka-consumer-groups.sh --bootstrap-server 172.18.182.32:9092,172.18.182.33:9092,172.18.182.31:9092 --group UserCenterProd --describe
# 手動設(shè)置offset
bin/kafka-consumer-groups.sh --bootstrap-server 172.18.182.32:9092,172.18.182.33:9092,172.18.182.31:9092 --group UserCenterProd --reset-offsets --topic queuing-user-add --to-offset 20 --execute

三、基礎(chǔ)概念

  • broker:即節(jié)點
  • partition:分區(qū),消息會根據(jù)key進入不同的分區(qū),由不同的消費者(也可以相同,自動分配)消費。
    --replication-factor:備份,一般小于等于broker的數(shù)量。
  • ISR:leader會追蹤和維護ISR中所有follower的滯后狀態(tài)。如果滯后太多(數(shù)量滯后和時間滯后兩個維度,replica.lag.time.max.ms和replica.lag.max.message可配置),leader會把該replica從ISR中移除。被移除ISR的replica一直在追趕leader。如下圖,leader寫入數(shù)據(jù)后并不會commit,只有ISR列表中的所有folower同步之后才會commit,把滯后的follower移除ISR主要是避免寫消息延遲。設(shè)置ISR主要是為了broker宕掉之后,重新選舉partition的leader從ISR列表中選擇。(轉(zhuǎn)自 https://blog.csdn.net/dshf_1/article/details/82467558
  • consumer group: 同一個消費組中的不同消費者負責topic的一部分partition;如果是不同消費組,則獨立計算offset,即對一個topic消費多次。
  • zookeeper:分布式協(xié)調(diào)框架,負責協(xié)調(diào)管理并保存kafka的元數(shù)據(jù),比如哪些broker在運行,創(chuàng)建了哪些topic,它們有哪些分區(qū),leader在哪。

四、集群環(huán)境建議

因素 考量點 建議
操作系統(tǒng) 操作系統(tǒng)I/O模型 Linux
磁盤 磁盤I/O性能 普通機械硬盤,不需要RAID
磁盤容量 根據(jù)消息量和留存時間預估 建議多預留30%空間
帶寬 根據(jù)業(yè)務(wù) 如果千兆貸款,建議按照700Mbps來計算

五、最重要的集群參數(shù)配置

1)broker端參數(shù)

參數(shù) 設(shè)置建議 概述
log.dir 可以不設(shè)置 一般設(shè)置log.dirs
log.dirs /home/kafka1,/home/kafka2 設(shè)置在不同的物理磁盤上可以提升讀寫性能,實現(xiàn)failover
zookeeper.connect zk1:2181,zk2:2181,zk2:2181/kafka1 可以多個kafka集群共用一個zk集群
listeners 協(xié)議://HOST_NAME:9092 外部連接要通過什么協(xié)議訪問指定主機名和端口開放的kafka服務(wù)
advertised.listeners 協(xié)議://HOST_NAME:9092 這組監(jiān)聽器是Broker用于對外發(fā)布的,會存在zookeeper中
host.name/port 不要填這兩個,早就不用了
auto.create.topics.enable false 不要開啟自動創(chuàng)建
unclean.leader.election.enable false 不要unclean選舉
auto.leader.rebalance.enable false 關(guān)閉定時選舉
log.retention.hours 168 數(shù)據(jù)保存7天
log.retention.bytes 根據(jù)空閑硬盤設(shè)定 防止服務(wù)器爆
message.max.bytes 1000120 kafka最大消息大小,默認是100012

2)topic端參數(shù)

參數(shù) 設(shè)置建議 概述
retention.ms 數(shù)據(jù)保存時間
retention.bytes 預留空間
max.message.bytes 1000120 kafka最大消息大小,默認是100012
replica.fetch.max.bytes 1000120 根據(jù)max.message.bytes設(shè)置保證復制
fetch.message.max.bytes 1000120 根據(jù)max.message.bytes設(shè)置保證消費

3)JVM參數(shù)

在啟動kafka前配置java的默認堆大小

$> export KAFKA_HEAP_OPTS=--Xms6g  --Xmx6g
$> export KAFKA_JVM_PERFORMANCE_OPTS= -server -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+ExplicitGCInvokesConcurrent -Djava.awt.headless=true
$> bin/kafka-server-start.sh config/server.properties

4)操作系統(tǒng)參數(shù)

ulimit -n 1000000

文件系統(tǒng)可以選擇XFS
swappiess設(shè)置為1
落盤時間可以適當延長

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容