kafka 的基本操作
topic的CRUD
对应的脚本是kafka-topics.sh
参数
Create, delete, describe, or change a topic.
Option Description
------ -----------
--alter 修改分区数量,只能增加分区
--create Create a new topic.
--delete Delete a topic
--help Print usage information.
--list List all available topics.
--partitions <Integer> 用来指定分区数量
--replication-factor <Integer> 用于指定副本总数,就是一个分区的所有副本数量
--topic <String: topic> 主题名称
--zookeeper <String: hosts> 是一个必需属性,可以指定多个zookeeper服务,万一指定一个恰好是宕机的
案列
创建主题
kafka-topics.sh \
--create \
--topic pet \
--partitions 3 \
--replication-factor 2 \
--zookeeper qianfeng01,qianfeng02,qianfeng03/kafka
查看主题
kafka-topics.sh \
--list \
--zookeeper qianfeng01,qianfeng02,qianfeng03/kafka
查看指定主题
kafka-topics.sh \
--describe \
--topic pet \
--zookeeper qianfeng01,qianfeng02,qianfeng03/kafka
修改主题
注意
修改主题只能把主题的分区数量增大
kafka-topics.sh \
--alter \
--partitions 4 \
--topic pet \
--zookeeper qianfeng01,qianfeng02,qianfeng03/kafka
删除主题
kafka-topics.sh \
--delete \
--topic pet \
--zookeeper qianfeng01,qianfeng02,qianfeng03/kafka
kafka生产、消费消息
生产消息
脚本kafka-console-producer.sh 参数如下
kafka-console-producer.sh
Read data from standard input and publish it to Kafka.
Option Description
------ -----------
--batch-size <Integer: size> 批处理发送数据时指定的一次发送的消息的条数。默认200
--broker-list <String: broker-list> REQUIRED: 指定broker列表
--request-required-acks <String: The required acks of the producer
request required acks> requests (default: 1)
--topic <String: topic> REQUIRED: 用来指定主题
案例
kafka-console-producer.sh \
--broker-list qianfeng01:9092,qianfeng02:9092,qianfeng03:9092 \
--topic pet \
消费者消费消息
脚本kafka-console-consumer.sh 参数如下
[root@qianfeng02 ~]# kafka-console-consumer.sh
The console consumer is a tool that reads data from Kafka and outputs it to standard output.
Option Description
------ -----------
--bootstrap-server <String: server to> REQUIRED: 连接broker服务器
--from-beginning 从头开始消费消息
--group <String: consumer group id> 将消费者划分消费者组
--offset <String: consume offset> 可以指定一个非负数的偏移量,
or 'earliest' 表示从头开始消费
or 'latest' 消费新消息,默认是latest
--partition <Integer: partition> 指定消费的具体分区号
--topic <String: topic> 指定消费的主题
--zookeeper <String: urls> REQUIRED:zookeeper集群(高版本不用加)
案例
默认情况,消费最新消息
kafka-console-consumer.sh \
--bootstrap-server qianfeng01:9092,qianfeng02:9092,qianfeng03:9092 \
--topic pet
从头消费信息,所有分区的消息
kafka-console-consumer.sh \
--bootstrap-server qianfeng01:9092,qianfeng02:9092,qianfeng03:9092 \
--topic pet \
--from-beginning
指定分区,指定偏移量消费消息--------> 指定非负数形式
kafka-console-consumer.sh \
--bootstrap-server qianfeng01:9092,qianfeng02:9092,qianfeng03:9092 \
--topic pet \
--partition 0 \
--offset 2
指定分区,指定偏移量消费消息--------> 指定从头消费
kafka-console-consumer.sh \
--bootstrap-server qianfeng01:9092,qianfeng02:9092,qianfeng03:9092 \
--topic pet \
--partition 0 \
--offset earliest