[Kafka Cookboook] Simple Producer

Now that we have completed a Quick Start, let's see how to write a basic Java Producer for Kafka.

Pre-Conditions
Kafka setup is up and running (including Zookeeper)

If you are using Maven, here are the needed dependencies

The producer is going to be simple, which would just be in a loop and send a message with a delay.
The purpose is just to write a simple producer and explore the API.

Here is the Code

Let's look at the code. The initial part deals with configuration options like Bootstrap host Address from where it would fetch further information. Key and Value Serializer are the options used to convert to binary form and vise-versa. Using the configuration, we instantiate a Kafka Producer. Sending the message is simple, we need to create a ProducerRecord with desired key and value and call send() on producer instance.

That's it. The example sends 1000 messages, you can configure in the way you like.

Leave a Reply

Your email address will not be published. Required fields are marked *