在進行kafka集羣搭建前需要準備環境:
1.jdk的本版 jdk8(zk,kafka官網文檔有要求)
2.kafka版本kafka_2.12-2.4.0 (如果爲其他本版,請查看對應的libs下對應的 zk的版本,本版不一致可能會導致環境問題)
3.zk版本 zookeeper-3.5.6(源碼方式,不喜歡看的繞過,麻煩尊重一下文章發表者,畢竟你要是擼出來了也就用不着看這個文章;不足之處敬請指正待後續更改)
4.maven環境(zookeeper-3.5.6使用,打包一下,不然啓動不了;maven鏡像設置,報錯解決辦法文中有描述,此文超長超臭,請原諒我這個中文佔五渣的!!!!!!)
5.虛擬機上建的服務器列表規劃(本文只用三個,集羣可參考zk官網)
#####################001軟件版本(部分去掉前綴)#####################
[root@localhost apps]# ll
總用量 189612
drwxr-xr-x. 6 root root 99 1月 18 08:03 apache-maven-3.6.3
drwxr-xr-x. 7 10 143 245 10月 5 06:13 jdk1.8.0_231
-rw-r--r--. 1 root root 194151339 1月 12 03:17 jdk-8u231-linux-x64.tar.gz
drwxr-xr-x. 7 root root 101 1月 17 09:26 kafka_2.12-2.4.0
drwxrwxr-x. 6 root root 4096 1月 16 11:47 redis-5.0.7
drwxr-xr-x. 14 root root 4096 1月 18 07:35 zookeeper-3.5.6
#####################軟件版本(部分去掉前綴)#####################
####################002 ZK配置文件 文章最後有 start ################################
[root@localhost config]# cd /usr/local/apps/kafka_2.12-2.4.0/config
包括日誌:
監聽:listeners=PLAINTEXT://192.168.23.12:9092
brokerid: broker.id=2(與myid文件中的數字一直)
zk:zookeeper.connect=192.168.23.12:2181,192.168.23.13:2181,192.168.23.14:2181
####################ZK配置文件 文章最後有 end ################################
接下來你要去install 並package一下zookeeper-server下的東西(不然無法啓動zk)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
[root@localhost zookeeper-server]# cd /usr/local/apps/zookeeper-3.5.6/zookeeper-server
[root@localhost zookeeper-server]# ll
總用量 16
-rwxrwxr-x. 1 hadoop hadoop 9162 10月 8 16:14 pom.xml
drwxrwxr-x. 4 hadoop hadoop 30 10月 5 07:27 src
drwxr-xr-x. 11 root root 4096 1月 18 08:44 target
[root@localhost zookeeper-server]# mvn install -Dmaven.test.skip=true
[root@localhost zookeeper-server]# mvn package -Dmaven.test.skip=true
###################003 kafka配置文件############################################
這兩個減一半(根據官網搭建最小的zk集羣配)
initLimit=5
syncLimit=2 (leader 與follower的最小配置)
zk存放數據的地方
dataDir=/usr/local/apps/zookeeper-3.5.6/data
服務列表:(文中部分地方用了192.168.23.11展示,踩坑過程,過程正確maven install原因)
server.2=192.168.23.12:2888:3888
server.3=192.168.23.13:2888:3888
server.4=192.168.23.14:2888:3888
###################kafka配置文件 end ############################################
#######################wget地址#############################################
1.jdk 註冊賬號去oracle官網下
1.1 zk
wget http://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/current/apache-zookeeper-3.5.6.tar.gz
zk對應的kafka的jar(也就是這些,看看下載的zk的jar是哪個版本,然後下就行了)
-rw-r--r--. 1 root root 984810 10月 20 06:21 zookeeper-3.5.6.jar
-rw-r--r--. 1 root root 250329 10月 20 06:21 zookeeper-jute-3.5.6.jar
[root@localhost libs]# cd /usr/local/apps/kafka_2.12-2.4.0/libs
1.2 maven
wget http://mirror.bit.edu.cn/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz
1.3
wget http://mirrors.tuna.tsinghua.edu.cn/apache/kafka/2.4.0/kafka_2.12-2.4.0.tgz
#######################wget地址#############################################
zk集羣搭建官網位置(http://zookeeper.apache.org/doc/r3.5.6/zookeeperStarted.html#sc_RunningReplicatedZooKeeper),英文看不懂翻譯軟件搞一下,文中有不對之處多多指教
1.kafka官網download(http://kafka.apache.org/quickstart),並解壓文件
[root@localhost ~]# wget http://mirror.bit.edu.cn/apache/kafka/2.4.0/kafka_2.12-2.4.0.tgz
[root@localhost ~]# tar -zxvf kafka_2.12-2.4.0.tgz
[root@localhost ~]# mv kafka_2.12-2.4.0 /usr/local/apps/
2.看一下kafka使用的zookeeper版本 kafka_2.12-2.4.0.tgz對應的zookeeper-3.5.6.jar 版本不對可能會導致兼容性問題;
若發現zk啓動不了,請看文文章後面關於zk啓動報錯解決方式(因爲zookeeper-3.5.6用maven打某些jar)
zookeeper-3.5.6.jar
zookeeper-jute-3.5.6.jar
3.下載zookeeper 首先去官網 (https://www.apache.org/dyn/closer.cgi/zookeeper/ )之後點進去複製鏈接,當然也可以從其他鏡像地址下載
[root@localhost libs]# wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.5.6/apache-zookeeper-3.5.6.tar.gz
4.配置zk
/usr/local/apps/apache-zookeeper-3.5.6
看官網介紹
http://zookeeper.apache.org/doc/r3.5.6/zookeeperStarted.html
5.說要配置zoo.cfg ( [root@localhost conf]# mv zoo_sample.cfg zoo.cfg )
To start ZooKeeper you need a configuration file. Here is a sample, create it in conf/zoo.cfg:
官網文檔往下,配值這些,根據文檔那就建這些文件夾以及文件 ;調整一下dataDir的位置
tickTime=2000
dataDir=/var/lib/zookeeper
clientPort=2181
initLimit=5
syncLimit=2
server.1=zoo1:2888:3888
server.2=zoo2:2888:3888
server.3=zoo3:2888:3888
6.建文件夾
[root@localhost apache-zookeeper-3.5.6]# mkdir data
[root@localhost apache-zookeeper-3.5.6]# cd data
[root@localhost data]# vi myid
插入1 第一臺,第二臺改爲2 第三臺改爲3( i--->esc----shift+:-----wq )
到zookeeper中建 zk運行存放數據的目錄
[root@localhost conf]# vi zoo.cfg
[root@localhost apps]# cd apache-zookeeper-3.5.6/
[root@localhost apache-zookeeper-3.5.6]# mkdir zkdata
[root@localhost apache-zookeeper-3.5.6]# pwd
/usr/local/apps/apache-zookeeper-3.5.6
[root@localhost apache-zookeeper-3.5.6]#
配置ip地址
本機單節點也可以玩,文檔最後有說明,就是說通訊:選舉端口( 2888:3888)配置不一樣,同時clientPort配置不一樣(clientPort=2181 要不一樣,dataDir 地址不一樣(如果當前zk文件夾下就可以一樣,因爲不同文件夾下的相同文件夾名稱也是不同的),很容易理解就是一臺機器的端口衝突)
If you want to test multiple servers on a single machine, specify the servername as localhost with unique quorum & leader election ports (i.e. 2888:3888, 2889:3889, 2890:3890 in the example above) for each server.X in that server's config file. Of course separate _dataDir_s and distinct _clientPort_s are also necessary (in the above replicated example, running on a single localhost, you would still have three config files).
7.其他幾臺機器上一樣配置
8.啓動到zk的bin目錄下啓動zookeeper(等kafka配置好了先啓動zk)
bin/zkServer.sh start
9配置kafka
官網上擼,先囉嗦半天,到步驟10看具體的配置
http://kafka.apache.org/quickstart
集羣說明要配置的(但到配置文件裏說明的更多)還是看config下的文件配置說明
看這段描述,也就是說broker.id是區分集羣中的節點信息的:The broker.id
property is the unique and permanent name of each node in the cluster
10.配置 進入kafka的配置目錄
[root@localhost config]# pwd
/usr/local/apps/kafka_2.12-2.4.0/config
10.1編輯 server.properties
[root@localhost config]# vi server.properties
10.2配置文件中的broker.id修改一下,其他兩臺也不一樣(步驟9中有說明)
############################# Server Basics #############################
# The id of the broker. This must be set to a unique integer for each broker.
broker.id=1
10.3 往下,監聽listeners=PLAINTEXT://192.168.23.11:9092 (其他配置自己的ip)
# 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
listeners=PLAINTEXT://192.168.23.11: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
10.4 配置日誌的目錄(自己提前先建一個logs文件夾,在路徑下)
############################# Log Basics #############################
# A comma separated list of directories under which to store log files
log.dirs=/usr/local/apps/kafka_2.12-2.4.0/logs
10.5 配置zookeeper的連接(kafka依賴zk的,到zk上註冊節點信息,2181就是之前配置zk中有的clientPort,理解就是客戶端連接端口)
樣例中有說明:# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". 就是IP:Port (ip和端口,逗號分隔)
# 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.connect=192.168.23.11:2181,192.168.23.12:2181,192.168.23.13:2181
################# 安裝過程可能遇到諸多問題: zk啓動不起來,檢查問題 start #################
檢查:1.配置zk的文件 2.maven是否安裝,並且已經打包了
1.看日誌報錯 QuorumPeerMain
[root@localhost bin]# ./zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /usr/local/apps/zookeeper-3.5.6/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Error contacting service. It is probably not running.
看日誌(學會看日誌還是很重要的):
[root@localhost zookeeper-3.5.6]# cd logs
[root@localhost logs]# cat logs
cat: logs: 沒有那個文件或目錄
[root@localhost logs]# ll
總用量 4
-rw-r--r--. 1 root root 89 1月 18 07:51 zookeeper-root-server-localhost.localdomain.out
[root@localhost logs]# cat zookeeper-root-server-localhost.localdomain.out
錯誤: 找不到或無法加載主類 org.apache.zookeeper.server.quorum.QuorumPeerMain
2.那麼裝maven(https://blog.csdn.net/baidu2030/article/details/92367795)
下載maven,設置鏡像
[root@localhost apps]# wget http://mirror.bit.edu.cn/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz
[root@localhost apps]# tar -zxvf apache-maven-3.6.3-bin.tar.gz
[root@localhost conf]# pwd
/usr/local/apps/apache-maven-3.6.3/conf
[root@localhost conf]# vi settings.xml
設置setting.xml的鏡像,改爲阿里鏡像,當然其他鏡像也可以
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
設置maven_home 並生效,查看maven生效
[root@localhost conf]# vi /etc/profile
export MAVEN_HOME=/usr/local/apps/apache-maven-3.6.3
export PATH=$MAVEN_HOME/bin:$PATH
[root@localhost conf]# source /etc/profile
[root@localhost conf]# mvn -v
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/local/apps/apache-maven-3.6.3
本地安裝(zookeeper-3.5.6/zookeeper-server)
[root@localhost zookeeper-server]# pwd
/usr/local/apps/zookeeper-3.5.6/zookeeper-server
maven 錯誤可以參考:https://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
[root@localhost zookeeper-server]# mvn install -Dmaven.test.skip=true
[root@localhost zookeeper-server]# mvn package -Dmaven.test.skip=true
啓動成功,也就市zk啓動成功了
[root@localhost bin]# ./zkServer.sh start
ZooKeeper JMX enabled by default
Using config: /usr/local/apps/zookeeper-3.5.6/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED
[root@localhost bin]# ./zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /usr/local/apps/zookeeper-3.5.6/bin/../conf/zoo.cfg
Client port found: 2181. Client address: localhost.
Mode: follower
#################安裝過程可能遇到諸多問題: zk啓動不起來,檢查問題 end #################
接下來啓動kafka,有木有啓動成功呢?測一下,官網上建topic的方式
啓動:[root@localhost bin]# ./kafka-server-start.sh -daemon ../config/server.properties
其他幾臺服務器也是一樣提前進入準備
啓動並創建topic消費
[root@localhost bin]# pwd
/usr/local/apps/kafka_2.12-2.4.0/bin
[root@localhost bin]# ./kafka-server-start.sh -daemon ../config/server.properties
[root@localhost bin]# ./kafka-console-producer.sh --broker-list 192.168.23.12:9092 --topic test
>This is a message
[2020-01-18 09:21:21,982] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {test=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2020-01-18 09:21:22,102] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 4 : {test=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
[2020-01-18 09:21:22,221] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 5 : {test=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
>This is another message
>/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D^H^H^C[root@localhost bin]# /kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning^C
[root@localhost bin]# ./kafka-console-consumer.sh --bootstrap-server 192.168.23.12:9092 --topic test --from-beginning
This is a message
This is another message
####################################01 kafka配置 start########################################
[root@localhost config]# cat 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=2
############################# 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
listeners=PLAINTEXT://192.168.23.12: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=/usr/local/apps/kafka_2.12-2.4.0/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.connect=192.168.23.12:2181,192.168.23.13:2181,192.168.23.14: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配置 end########################################
測試代碼:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.4.0</version>
</dependency>
public class KafkaTest {
public static void main(String[] args) {
producer(); //生產者
consumer(); //消費者
}
/**
* 生產者
*/
public static void producer(){
Properties pp = new Properties();
pp.put("bootstrap.servers","192.168.23.12:9092");
pp.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
pp.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
pp.put("acks", "all");
pp.put("linger.ms", 1);
pp.put("retries", 0);
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(pp);
for (int i = 0; i <10 ; i++) {
ProducerRecord producerRecord = new ProducerRecord("mytopic", "key:" + Integer.toString(i), " value:" + Integer.toString(i));
producer.send(producerRecord);
}
producer.flush();
producer.close();
}
/**
* 消費者
*/
public static void consumer(){
Properties pp2 = new Properties();
pp2.put("bootstrap.servers","192.168.23.12:9092");
pp2.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
pp2.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
pp2.put("enable.auto.commit", true);
pp2.put("group.id", "groupA");
pp2.put("session.timeout.ms", 30000);
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(pp2);
consumer.subscribe(Arrays.asList("mytopic")); //訂閱話題
while (true) {
ConsumerRecords<String, String> poll = consumer.poll(100);
for (ConsumerRecord<String, String> record : poll) {
System.out.println("offset:"+record.offset()+" key:"+record.key()+" value:"+record.value());
}
//理論上一直在消費
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}