In the previous topic, we have covered about how to setup kafka cluster on windows and create kafka topic. Please check the previous topic of Create Kafka Cluster , Kafka Consumer , Kafka Producer , Kafka Topics to understand the kafka setup, kafka broker and kafka topic creation so that you can easily create a Java program for the Kafka Producer.
In this article you will learn about how to write and publish kafka messages in Java. You can see the below example of Java program to write and publish Kafka messages in Java.
<
dependency> <
groupId> org.apache.kafka <
/groupId> <
artifactId> kafka-clients <
/artifactId> <
version> 0.9.0.0 <
/version> <
/dependency>
import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import java.util.Properties; import org.apache.kafka.clients.consumer.*; import org.apache.kafka.common.serialization.StringDeserializer; public class KafkaProducerExample { static String TOPIC_NAME= "first-topic"; public static void main(String args[]){ try { Properties p = new Properties(); p.setProperty( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092" ); p.setProperty( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName() ); p.setProperty( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName() ); KafkaProducer<
String, String
> producer = new KafkaProducer<>(p); producer.send(new ProducerRecord<>(TOPIC_NAME, "I am Good!")); producer.send(new ProducerRecord<>(TOPIC_NAME, "What about You?")); producer.send(new ProducerRecord<>(TOPIC_NAME, "Hope you are also well?")); producer.flush(); producer.close(); }catch(Exception e){ e.printStackTrace(); } } }
kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic first-topic --from-beginning
In the next topic, you will understand about how to read kafka message in java. See the details of
Read Kafka Messages In Java