Skip to content
Advertisement

Spring Kafka Template – Connect to Kafka Topic on Spring Boot Startup

I have implemented a basic Spring Boot Application which uses Spring Kafka. I want my producer to connect to the Kafka Topic before the first .send() is called but I can’t find a way to do so. Is that possible?

Logs to show that KafkaTemplate only connects to the Kafka Topic after I trigger the .send method at 16:12:44:

JavaScript

Advertisement

Answer

With non-transactional producer (transactionIdPrefix is not supplied), when you first call KafkaTemplate.send, it will delegate to ProducerFactory to get a single instance of Producer. At this time, because there’s no a single instance of Producer before, ProducerFactory will create this one for you (that’s why you saw the log ProducerConfig : ProducerConfig values ...). This producer instance is now used/shared by all clients.


So if you want to create the above producer instance beforehand, you could directly call it on the ProducerFactory, e.g:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement