1. 启停kafka
- 启动kafka
# -daemon 以后台运行的方式启动
sh bin/kafka-server-start.sh -daemon config/server.properties
- 停止kafka
sh bin/kafka-server-stop.sh
2. topic相关
- 创建topic
# --zookeeper 指定zookeeper的IP:Port
# --partitions 指定topic的分区数
# --replication-factor 指定每个分区的副本数
# --topic 指定topic的名称
sh bin/kafka-topics.sh --create --zookeeper localhost:2181 --partitions 3 --replication-factor 1 --topic spurs
# 如下结果表示创建成功
Created topic "spurs"
- 查看所有topic
bin/kafka-topics.sh --list --zookeeper localhost:2181
# 显示结果如下
__consumer_offsets
spurs
- 查看topic的分区及副本
sh bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic spurs
# 显示结果如下
Topic:spurs PartitionCount:3 ReplicationFactor:1 Configs:
Topic: spurs Partition: 0 Leader: 19 Replicas: 19 Isr: 19
Topic: spurs Partition: 1 Leader: 19 Replicas: 19 Isr: 19
Topic: spurs Partition: 2 Leader: 19 Replicas: 19 Isr: 19
- 查看topic在分区上的偏移
sh kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092 --topic spurs --time -1
# 显示结果如下
spurs:2:0
spurs:1:0
spurs:0:0
# 注1 结果格式为: topic名称:partition分区号:分区的offset
# 注2 --time 为 -1时用来请求分区最新的offset
# --time 为 -2时用来请求分区最早有效的offset
3. 生产消费
- 往topic发送消息
sh bin/kafka-console-producer.sh --broker-list localhost:9092 --topic spurs
# 输入命令后, 出现 > 提示符, 输入消息内容, 回车表示结束输入并发送, 如下输入12条消息
> Aldridge
> Leonard
> Gasol
> Parker
> Mills
> Green
> Gay
> Ginobili
> Anderson
> Forbes
> Murray
> Bertans
# 再次查看分区的偏移信息
sh bin/kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list localhost:9092 --topic spurs --time -1
# 输出结果如下
spurs:2:4
spurs:1:4
spurs:0:4
- 从topic消费消息
sh bin/kafka-console-consumer.sh --topic spurs --bootstrap-server localhost:9092 --from-beginning
# 可以增加 --partition 选项 从指定的分区消费消息
# 可以增加 --offset 选项 从指定的偏移位置消费消息
# 可以增加 --group 选项 以指定消费者组的形式消费消息
# 可以增加 --max-messages 选项 指定消费消息的最大个数
# 例如 创建hncscwc消费者组, 并从 2号分区 偏移量为1的位置开始消费 2条消息
sh bin/kafka-console-consumer.sh --topic spurs --group hncscwc --partition 2 --offset 1 --max-messages 2 --bootstrap-server localhost:9092
# 结果如下
Mills
Ginobili
Processed a total of 2 messages
- 查看所有消费者组
sh bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list
# 结果如下
Note: This will not show information about old Zookeeper-based consumers.
console-consumer-22568
hncscwc
- 查看消费者组的详细信息
sh bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group hncscwc
# 结果如下
Note: This will not show information about old Zookeeper-based consumers.
Consumer group 'hncscwc' has no active members.
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
spurs 0 4 4 0 - - -
spurs 2 4 4 0 - - -
spurs 1 4 4 0 - - -