After installing Apache Kafka, you can use the Apache Kafka CLI tool to work with topics in the Apache Kafka server.
Create a new topic
We will use the Apache Kafka CLI’s kafka-topics.sh file to work with topics in the Apache Kafka server.
To create a new topic, you can use the command with the following syntax:
1 |
kafka-topics.sh --create --topic <topic_name> --bootstrap-server <kafka_server> --partitions <partition_number> --replication-factor <replication_number> |
In there:
- topic_name is the topic name that we need to create.
- kafka_server is the address of the Apache Kafka server with the format host:port.
- partition_number is the number of partitions we need to create.
- replication_number is the number of replications we want for each partition. The value of this parameter will depend on how many Apache Kafka servers we have.
For example, I run the following command:
1 |
kafka-topics.sh --create --topic huongdanjava --bootstrap-server localhost:9092 --partitions 2 --replication-factor 1 |
The result will be as follows:
To check the topic we just created above in the Apache Kafka server, you can run the following command:
1 |
kafka-topics.sh --describe --topic <topic_name> --bootstrap-server <kafka_server> |
The meaning of the parameters as I mentioned above.
My example is as follows:
1 |
kafka-topics.sh --describe --topic huongdanjava --bootstrap-server localhost:9092 |
Result:
As you can see, my topic huongdanjava has 2 partitions and the number of ReplicationFactor is 1 as the command I ran above.
View all topics
To check all topics contained in an Apache Kafka server, you can run the following command:
1 |
kafka-topics.sh --list --bootstrap-server <kafka_server> |
An example is as follows:
1 |
kafka-topics.sh --list --bootstrap-server localhost:9092 |
You will see the topic we just created above as follows:
View all messages in a topic
To see all messages in an Apache Kafka topic, you can use the following command:
1 |
kafka-console-consumer.sh --bootstrap-server <kafka_server> --topic <topic_name> --from-beginning |
For example:
1 |
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic huongdanjava --from-beginning |
The result when I run this command is as follows:
Currently, in my example topic, there are no messages but if a new message arrives, it will be displayed here!
Delete a topic
To delete a topic in the Apache Kafka server, we will use the following command:
1 |
kafka-topics.sh --delete --topic <topic_name> --bootstrap-server <kafka_server> |
My example is as follows:
1 |
kafka-topics.sh --delete --topic huongdanjava --bootstrap-server localhost:9092 |
Result: