本文在《kafka 集群搭建步骤》的基础上,总结下 kafka 的常用操作命令。
一、集群
1.1 启动集群
分别在三台服务器上执行如下命令,启动集群:
[cpctest@vm-10-201-42-13 bin]$ pwd
/home/cpctest/kafka_2.13-2.8.1/bin
[cpctest@vm-10-201-42-13 bin]$ ./kafka-server-start.sh -daemon /home/cpctest/kafka_2.13-2.8.1/config/server.properties
[cpctest@vm-10-201-42-13 bin]$ jps
5584 Jps
5538 Kafka
26757 jar
24125 QuorumPeerMain
1.2 停止 kafka
[cpctest@vm-10-201-42-13 bin]$ pwd
/home/cpctest/kafka_2.13-2.8.1/bin
[cpctest@vm-10-201-42-13 bin]$ ./kafka-server-stop.sh
二、主题操作
2.1 查看主题列表
[cpctest@vm-10-201-42-13 bin]$ ./kafka-topics.sh --list --zookeeper 10.201.42.13:2181,10.201.42.14:2181,10.201.42.26:2181
test_topic
2.2 查看指定主题的详细信息
[cpctest@vm-10-201-42-13 bin]$ ./kafka-topics.sh --describe --zookeeper 10.201.42.13:2181,10.201.42.14:2181,10.201.42.26:2181 --topic test_topic
Topic: test_topic TopicId: px_1ap8DRyGEYtn_ca0b1w PartitionCount: 1 ReplicationFactor: 1 Configs:
Topic: test_topic Partition: 0 Leader: 1 Replicas: 1 Isr: 1
2.3 删除主题
[cpctest@vm-10-201-42-13 bin]$ ./kafka-topics.sh --delete --zookeeper 10.201.42.13:2181,10.201.42.14:2181,10.201.42.26:2181 --topic test_topic
Topic test_topic is marked for deletion.
Note: This will have no impact if delete.topic.enable is not set to true.
2.4 创建主题
创建 topic 命令的几个属性含义如下:
--create:表示创建
--zookeeper:后面的参数是 zk 的集群节点
--replication-factor 1:表示复本数是1,或者副本因子是 1
--partitions 1:表示分区数是 1
--topic test_topic:表示主题名称是 test_topic
[cpctest@vm-10-201-42-13 bin]$ ./kafka-topics.sh --create --zookeeper 10.201.42.13:2181,10.201.42.14:2181,10.201.42.26:2181 --replication-factor 1 --partitions 1 --topic test_topic
WARNING: Due to limitations in metric names, topics with a period ('.') or underscore ('_') could collide. To avoid issues it is best to use either, but not both.
Created topic test_topic.
三、生产者客户端
创建生产者客户端并发送消息 “hello world”
[cpctest@vm-10-201-42-13 bin]$ ./kafka-console-producer.sh --broker-list 10.201.42.13:9092,10.201.42.14:9092,10.201.42.26:9092 --topic test_topic
>hello world
>
发送消息时,直接在生产者客户端中输入消息即可,如上所示。
四、消费者客户端
创建消费者客户端并消费消息:
[cpctest@vm-10-201-42-14 bin]$ ./kafka-console-consumer.sh --bootstrap-server 10.201.42.13:9092,10.201.42.14:9092,10.201.42.26:9092 --topic test_topic
hello world