Apache Kafka is a distributed streaming platform that allows you to publish and subscribe to streams of data. In this tutorial, you will learn how to use the Apache Kafka command-line interface (CLI) to produce messages to Kafka topics.
To produce messages to Kafka topics without a key, we nee to use the kafka-console-producer.sh script that comes with the Kafka installation. This script allows you to send messages to a Kafka topic from the standard input (stdin). Before we run the script, we need to make sure to bring up the kafka cluster.
Let's, asume that the Kafka cluster running on localhost:9092. This can be changed to match your cluster configuration.
To produce messages to a Kafka topic called product-created-events-topic, we need to run the following command in a terminal:
./kafka-console-producer.sh --bootstrap-server localhost:9092 --topic product-created-events-topic
Messages in Kafka topics are stored as a key-value pair. If you send a message without a key, then the key is null. However, sometimes you may want to send a message with a key, for example, to ensure that messages with the same key are stored in the same partition, and thus preserve the order of the messages.
To produce messages to Kafka topics with a key, you will use the same kafka-console-producer.sh script, but with some additional properties. The first property is parse.key=true, which tells the producer to expect each message to be in the format of key:value. The second property is key.separator=:, which tells the producer what character to use to separate the key and the value in each message.
To produce messages with a key to the same topic product-created-events-topic, you can run the following command in a terminal:
./kafka-console-producer.sh --bootstrap-server localhost:9092 --topic product-created-events-topic --property "parse.key=true" --property "key.separator=:"
After you run the command, you will see a > prompt, indicating that the producer is ready to accept messages from stdin.
You can type any message you want, as long as it follows the key:value format, and press enter to send it to the topic. For example: