Sunday 3 November 2019

Kafka CLI: Send message to a topic


Below statement is used to send a message to topic.

kafka-console-producer.sh --broker-list {kafkaServiceDetails} --topic {topicName}

Let’s see it with an example.

Step 1: Create a topic.
kafka-topics.sh --bootstrap-server localhost:9092 --topic myFirstTopic --create --partitions 3 --replication-factor 1

Step 2: Send some message to topic by executing below command.
kafka-console-producer.sh --broker-list localhost:9092 --topic myFirstTopic
$kafka-console-producer.sh --broker-list localhost:9092 --topic myFirstTopic
>Hey Kafka,
>This is my first message.
>^C

Once you enter the message, type CTRL + C to come out of the prompt.

If above command executed successfully without any error, then the message is submitted to kafka successfully.

Note

If you send a message to topic, which is not exist, then kafka creates the topic.
$kafka-console-producer.sh --broker-list localhost:9092 --topic mySecondTopic
>Hey kafka, I am sending message to a topic which is not exist
[2019-10-05 20:04:43,936] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {mySecondTopic=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
>I am done
>^C

When you enter message to a topic which is not exist, kafka thrown below error

[2019-10-05 20:04:43,936] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 :


But when you enter message again, kafka do not throw any error, since by this time kafka created a topic with name mySecondTopic. You can confirm the same by listing all topics.
$kafka-topics.sh --bootstrap-server localhost:9092 --list
myFirstTopic
mySecondTopic
$
$kafka-topics.sh --bootstrap-server localhost:9092 --topic mySecondTopic --describe
Topic:mySecondTopic PartitionCount:1 ReplicationFactor:1 Configs:segment.bytes=1073741824
 Topic: mySecondTopic Partition: 0 Leader: 0 Replicas: 0 Isr: 0





Previous                                                    Next                                                    Home

No comments:

Post a Comment