在进行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();
}
}
}
}
来源:CSDN
作者:haohaounique
链接:https://blog.csdn.net/haohaounique/article/details/104024820