![d7d98b38c4bf83bca76cf0380aa0320d.png](https://i-blog.csdnimg.cn/blog_migrate/db271e82e161144d2657e074692bdf31.png)
1. 启动 Kafka
Kafka 的 broker(也就是服务器)是由 Zookeeper 来管理的,所以启动 Kafka 之前需要先启动 Zookeeper。
zookeeper-server-start.sh config/zookeeper.properties
kafka-server-start.sh config/server.properties
2. Kafka Topics
创建一个名为 first_topic 的 topic,这里 partitions 和 replication-factor 参数都是必须的,而且 replication-factor 不能大于 broker 的数量。
kafka-topics
--bootstrap-server localhost:9092
--topic first_topic
--create
--partitions 3
--replication-factor 1
显示所有 topics:
kafka-topics
--bootstrap-server localhost:9092
--list
显示单个 topic 信息:
kafka-topics
--bootstrap-server localhost:9092
--topic first_topic
--describe
删除单个 topic:
kafka-topics
--bootstrap-server localhost:9092
--topic first_topic
--delete
3. Kafka Console Producer
Kafka producer 负责向 Kafka topics 发送消息。
kafka-console-producer
--broker-list localhost:9092
--topic first_topic
>hello
>world
>this is a new message
如果 producer 向不存在的 topic 发送消息,Kafka 会使用 config/server.properties 中的参数值自动创建这个 topic。
kafka-console-producer
--broker-list localhost:9092
--topic new_topic
>hello
[2020-01-09 01:27:00,889] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {new_topic=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
4. Kafka Console Consumer
Kafka consumer 负责读取 Kafka topics 里的消息。
kafka-console-consumer
--bootstrap-server localhost:9092
--topic first_topic
如果需要从头读取所有消息:
kafka-console-consumer
--bootstrap-server localhost:9092
--topic first_topic
--from-beginning
hello
this is a new message
world
这里读取的消息顺序并不一定是 producer 发送时的顺序,因为如果一个 topic 有多个 partitions,消息只在每个 partition 里是有序的。
5. Kafka Consumer Groups
在多个 Kafka consumers 读取同一 topic 中的消息时,可以指定一个 group,这样每一条消息只会被随机一个 consumer 读取:
kafka-console-consumer
--bootstrap-server localhost:9092
--topic first_topic
--group first_group
查询 group 的信息:
kafka-consumer-groups
--bootstrap-server localhost:9092
--list
kafka-consumer-groups
--bootstrap-server localhost:9092
--describe
--group first_group
![d392961e9ec17afabcd52c4b7fad152c.png](https://i-blog.csdnimg.cn/blog_migrate/fd20580594ea958e42e91683d123e9b1.png)