Should Kafka Producer be reused or short-lived?

Viewed 149

I have a test that uses EmbededKafka.

@Slf4j
@DirtiesContext
@SpringBootTest
@EmbeddedKafka(
        partitions = 1,
        brokerProperties = {
                "listeners=PLAINTEXT://localhost:9092",
                "port=9092"
        })
public class MyTest {
    @Lazy
    @Autowired
    @Qualifier("producerFactory")
    private ProducerFactory<String, MyData> producerFactory;

    @Test
    public void test() }
        sendMessage1();
        sendMessage2();
    }

    private void sendMessage1() {
        try (Producer<String, MyData> producer = producerFactory.createProducer()) {
            // Send the data 1 using producer
            producer.flush();
        }
    }

    private void sendMessage2() {
        try (Producer<String, MyData> producer = producerFactory.createProducer()) {
            // Send the data 2 using producer
            producer.flush();
        }
    }
}

In the above, I injected the Producer factory and created short-lived Kafka producer each time a message needs to be sent. The producer is closed after data is sent.

Another idea I have is to create the producer rather than producer factory in Spring TestConfiguration and inject it into the test, so that:

@Slf4j
@DirtiesContext
@SpringBootTest
@EmbeddedKafka(
        partitions = 1,
        brokerProperties = {
                "listeners=PLAINTEXT://localhost:9092",
                "port=9092"
        })
public class MyTest {
    @Lazy
    @Autowired
    @Qualifier("producer")
    private Producer<String, MyData> producer;

    @Test
    public void test() }
        sendMessage1();
        sendMessage2();
    }

    private void sendMessage1() {
        // Send the data 1 using injected producer to Topic A
        producer.flush();
        
    }

    private void sendMessage2() {
        // Send the data 2 using injected producer to Topic B
        producer.flush();
    }
}

Which one of these patterns are good practice for Kafka?

0 Answers
Related