To configure a Kafka producer to send messages to a specific topic, you need to specify the topic name when creating the ProducerRecord object. The ProducerRecord object represents a message that will be sent to a Kafka topic, and it contains the topic name, message key, and message value.
Here’s an example of how to configure a Kafka producer to send messages to a specific topic:
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
Producer producer = new KafkaProducer<>(props);
String topicName = "my_topic";
String key = "my_key";
String value = "my_message";
ProducerRecord record = new ProducerRecord<>(topicName, key, value);
producer.send(record);
producer.close();
In this example, we have defined the properties for the Kafka producer and created a Kafka producer instance. We have also defined the topic name, message key, and message value, and created a ProducerRecord object with these values. Finally, we have used the send method of the Kafka producer to send the message to the specified topic.
By specifying the topic name in the ProducerRecord object, you can configure the Kafka producer to send messages to a specific topic.