# JAVA: Create a Kafka Producer

In 
Published 2022-12-03

This tutorial explains to you how to create a Kafka producer from Java. This tutorial has an example as well.

A nice job to do is to write messages from an application, agent, etc to a Kafka topic. In this tutorial, I will explain to you how to write a message from a Java application.

First of all you must install a Kafka server in order to test it. For this example you don't need to install a Kafka cluster.

So, on my environment you have some prerequisites in order to test the Java code below.

PREREQUISITES:

  1. From the machine you run the Java client you must see the private Kafka server sockets (hostname:IP)

  2. You must have a Kafka topic named my-topic10

-- List all topics (prints only topic names)

kafka-topics.sh --list --zookeeper zookeeper1:2181/kafka

And now look at the code.

  • In pom.xml we must have kafka-clients:
 <dependency>
   <groupId>org.apache.kafka</groupId>
   <artifactId>kafka-clients</artifactId>
   <version>2.8.0</version>
</dependency>

And the class which creates the Kafka producer could be like this :

When you take a look at the Kafka Consumer, you must see something like this: