初识kafka即
一、kafka基本概念
一个典型的kafka体系架构包括若干个Producer、Consumer、broker及一个Zookeeper集群。Zookeeper是kafka用来负责集群元数据管理、控制器的选举等操作。
producer负责将消息发送到broker中,broker负责将接收到的数据写入到磁盘,而consumer负责从broker中消费消息。
kafka的体系结构图
从上图看出,kafka引入了如下3个术语:
- producer:生产者。发送消息的一方。生产负责生产消息,并把消息投递到broker中。
- broker:服务代理节点。可以简单的看成一个kafka实例。
- consumer:消费者。消费消息的一方。消费者连接到kafka上并接收消息,进行进行相应业务逻辑处理。
在kafka中,还有两个重要的概念:
- topic:主题。kafka中的消息以主题为单位进行归类,生产者负责将消息发送到特定的主题(producer发送给主题的每一条消息都必须指定一个主题),而消费者订阅一个主题并进行消费
- Partition:分区。主题是一个逻辑上的分区,它可以细分为多个分区,一个分区只能输入一个主题。
kafka消息分区示意图
每一个分区在存储层面可以看作是一个可追加的日志(log)文件。消息在被添加到分区日志文件的时候都会分配一个特定的偏移量(offset)。offset是消息在分区中的唯一标识,kafka通过它来保证消息在分区内的有序性,但是offset不是跨分区的。那么说明kafka只保证分区有序而不保证主题有序。
kafka通过增加分区来实现水平扩展,通过为分区引入多副本机制来提升容灾能力。同一个分区的不同副本中保存的消息是相同的,副本之间的关系是“一主多从”的关系。其中leader副本负责处理读写请求,foller副本只负责与leader副本的消息同步。kafka通过多副本机制实现了故障的自动转移,当kafka集群中的某个broker失效时任然能够保证服务的可用。
二、kakfa的安装与配置
搭建kafka运行环境还需要设计zookeeper,kafka及zookeeper都需要运行在JVM之上的服务,所以还需要安装JDK。首先验证是否已经成功安装了JDK
[root@localhost home]# java -version
java version "1.8.0_212"
Java(TM) SE Runtime Environment (build 1.8.0_212-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.212-b10, mixed mode)
[root@localhost home]#
笔记的虚拟机上已经成功安装了JDK8,没有安装的请自行百度安装。
zookeeper安装与配置
Zookeeper是安装kafka集群的必要组件,kafka通过zookeeper来实施对元数据信息的管理,包括集群、broker、主题、分区等内容。
-
下载相应的安装包,将安装包复制到/opt目录下,参考如下:
[root@localhost opt]# ll zookeeper-3.4.14.tar.gz
-rw-r–r--. 1 root root 37676320 3月 28 22:22 zookeeper-3.4.14.tar.gz[root@localhost opt]# tar -xzvf zookeeper-3.4.14.tar.gz
解压后当前/opt目录下生成一个名为 zookeeper-3.4.14的文件夹
[root@localhost opt]# cd zookeeper-3.4.14/
[root@localhost zookeeper-3.4.14]# pwd
/opt/zookeeper-3.4.14 -
进入zookeeper_home/conf目录,并将zoo_sample.cfg文件复制为zoo.cfg
修改zoo.cfg配置文件:
1 # The number of milliseconds of each tick 2 tickTime=2000 3 # The number of ticks that the initial 4 # synchronization phase can take 5 initLimit=10 6 # The number of ticks that can pass between 7 # sending a request and getting an acknowledgement 8 syncLimit=5 9 # the directory where the snapshot is stored. 10 # do not use /tmp for storage, /tmp here is just 11 # example sakes. 12 dataDir=/tmp/zookeeper/data 13 dataLogDir=/tmp/zookeeper/log 14 # the port at which the clients will connect 15 clientPort=2181 16 # the maximum number of client connections. 17 # increase this if you need to handle more clients 18 #maxClientCnxns=60 19 # 20 # Be sure to read the maintenance section of the 21 # administrator guide before turning on autopurge. 22 # 23 # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance 24 # 25 # The number of snapshots to retain in dataDir 26 #autopurge.snapRetainCount=3 27 # Purge task interval in hours 28 # Set to "0" to disable auto purge feature 29 #autopurge.purgeInterval=1
执行以下命令,创建目录
[root@localhost conf]# mkdir -p /tmp/zookeeper/data
[root@localhost conf]# mkdir -p /tmp/zookeeper/log -
进入zookeeper_home/bin目录,启动zookeeper
[root@localhost bin]# ./zkServer.sh start ZooKeeper JMX enabled by default Using config: /opt/zookeeper-3.4.14/bin/../conf/zoo.cfg Starting zookeeper ... STARTED
使用 zkCli连接zookeeper
[root@localhost bin]# ./zkCli.sh [root@localhost bin]# ./zkCli.sh Connecting to localhost:2181 2020-03-28 22:42:05,735 [myid:] - INFO [main:Environment@100] - Client ...... server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL (unknown error) Welcome to ZooKeeper! JLine support is enabled tiated timeout = 30000 WATCHER:: WatchedEvent state:SyncConnected type:None path:null [zk: localhost:2181(CONNECTED) 0]
这说明已经成功的安装并启动zookeeper
kafka的安装与配置
-
从官网下载安装包并复制到/opt目录下进行解压
[root@localhost opt]# tar -xzvf kafka_2.12-2.4.1.tgz
-
启动kafka的broker
[root@localhost kafka_2.12-2.4.1]# bin/kafka-server-start.sh config/server.properties
三、使用java客户端进行简单消息发送和接收
在pom文件中添加如下依赖:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.3.1</version>
</dependency>
要往kafka中写入消息,首先需要创建一个生产者客户端并设置一些配置参数,然后构建消息的ProducerRecord对象,进而通过生产者客户端将消息发送,最后通过close方法来关闭生产者。示例的代码如下:
public class ProducerDemo {
public static final String brokerList="192.168.195.133:9092";
public static final String topic = "topic-demo";
public static void main(String[] args) throws ExecutionException, InterruptedException {
Properties properties = new Properties();
properties.put("bootstrap.servers",brokerList);
//实例化produce
KafkaProducer<String,String> producer = new KafkaProducer<>(properties, new StringSerializer(),new StringSerializer());
//构建发送的记录
ProducerRecord<String,String> record = new ProducerRecord<>(topic,"hello","hell,kafka!");
//发送消息
Future<RecordMetadata> send = producer.send(record);
//阻塞等待发送的结果
send.get();
//关闭客户端
producer.close();
}
}
对应的消费消费消息也比较简单,首先创建一个KafkaConsumer类,订阅主题并消费即可。
public class ConsumerDemo {
public static final String brokerList="192.168.195.133:9092";
public static final String topic = "topic-demo";
public static void main(String[] args) throws ExecutionException, InterruptedException {
Properties properties = new Properties();
properties.put("bootstrap.servers",brokerList);
properties.put("group.id","group.demo");
//实例化consumer
KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties, new StringDeserializer(),new StringDeserializer());
consumer.subscribe(Collections.singleton(topic));
while(true){
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
Iterator<ConsumerRecord<String, String>> iterator = records.iterator();
while(iterator.hasNext()){
ConsumerRecord<String, String> record = iterator.next();
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
}
}
四、kafka服务端几个必要参数说明
- 1、zookeeper。connect:该参数指明broker要连接的zookeeper集群服务地址(包含端口号),没有默认值。是一个必填项。
- 2、listeners:指明broker监听客户端连接的地址列表,即客户端要连接broker的入口地址列表:
- 3、broker.id:kafka集群中broker的唯一标识
- 4、log.dir和log.dirs:这两个参数用来配置kafka日志文件存放的根目录。一般情况下,log.dir用来配置单个根目录,而log.dirs用来配置多个目录。但是kafka并没有对此做强制限制。log.dirs的优先级比log.dir高
- 5、message.max.bytes:指定所能接收消息的最大值,默认为976.6Kb,超过将会抛出异常–>RecordTooLargerException异常。