Kafka producer

In the publish and subscribe messaging system, the flow starts from the Publisher(which sends a piece of message to the broker(Kafka)).

Kafka comes with Client API , which will help to communicate with Kafka. The following is the example for the Kafka Producer, which will help you to understand how we are communicating with Kafka while sending the message(Record).

Kafka producer example

CopiedCopy Code
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
public class KafkaProducerExample {
	public static void main(String[] args) {
		ProducerRecord<String, String> record = new ProducerRecord<>("Producer","Producer");
		try {
			Properties props = new Properties();
			props.put("bootstrap.servers", "localhost:9092");
			props.put("client.id", "KafkaProducer");
			props.put("key.serializer", StringSerializer.class.getName());
			props.put("value.serializer", StringSerializer.class.getName());
			Producer<String, String> producer=new KafkaProducer(props);
			producer.send(record);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}