Can single Kafka producer produce messages to multiple topics and how?

Shankar picture Shankar · Aug 23, 2016 · Viewed 12.2k times · Source

I am just exploring Kafka, currently i am using One producer and One topic to produce messages and it is consumed by one Consumer. very simple.

I was reading the Kafka page, the new Producer API is thread-safe and sharing single instance will improve the performance.

Does it mean i can use single Producer to publish messages to multiple topics?

Answer

RadioLog picture RadioLog · Aug 23, 2016

Never tried it myself, but I guess you can. Since the code for producer and sending the record is (from here https://kafka.apache.org/090/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html):

Producer<String, String> producer = new KafkaProducer<>(props);
 for(int i = 0; i < 100; i++)
     producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i)));

So, I guess, if you just write different topics in the ProducerRecord, than it should be possible.

Also, here http://kafka.apache.org/081/documentation.html#producerapi it explicitly says that you can use a method send(List<KeyedMessage<K,V>> messages) to write into multiple topics.