Home > Software engineering >  One KafkaTemplate vs multiple KafkaTemplates
One KafkaTemplate vs multiple KafkaTemplates

Time:11-16

What is the recommended way to define KafkaTemplate when there are several different types of messages to send? Use just one KafkaTemplate for all messages (with Object) or define each KafkaTemplate for every type of messages?

One template KafkaTemplate with Object:

// Object
@Bean
ProducerFactory<String, Object> producerFactory() {
    return new DefaultKafkaProducerFactory<>(producerConfiguration());
}

@Bean
KafkaTemplate<String, Object> kafkaTemplate() {
    return new KafkaTemplate<>(producerFactory());
}

Or multiple KafkaTemplate:

// Address
@Bean
ProducerFactory<String, Address> addressProducerFactory() {
    return new DefaultKafkaProducerFactory<>(producerConfiguration());
}

@Bean
KafkaTemplate<String, Address> addressKafkaTemplate() {
    return new KafkaTemplate<>(addressProducerFactory());
}

// Person
@Bean
ProducerFactory<String, Person> personProducerFactory() {
    return new DefaultKafkaProducerFactory<>(producerConfiguration());
}

@Bean
KafkaTemplate<String, Person> personPafkaTemplate() {
    return new KafkaTemplate<>(personProducerFactory());
}

In the latter example ProducerFactory beans are also usually defined for every message type, which adds extra code. Do we really need them? It is ok just use a constructor, like this:

// Address
@Bean
KafkaTemplate<String, Address> addressKafkaTemplate() {
    return new KafkaTemplate<>(new DefaultKafkaProducerFactory<>(producerConfiguration()));
}

// Person
@Bean
KafkaTemplate<String, Person> personPafkaTemplate() {
    return new KafkaTemplate<>(new DefaultKafkaProducerFactory<>(producerConfiguration()));
}

CodePudding user response:

The generic type on KafakTemplate is really only important for receive() operations.

<Object, Object> is fine for most cases (i.e. not using receive).

However, Spring Boot auto configures a template with <?, ?> this allows you to inject it in multiple places with whatever generics you want. There is no need to specify multiple template beans.

Same thing with the producer and consumer factories.

CodePudding user response:

I think this may help you conclude your decision. You should go with a single generic KafkaTemplate<String, Object> even if the producer is publishing different types of value/data on multiple topics.

It is similar to having a JdbcTemplate in an application specific to a database and independent of a table. For one database, we keep one JdbcTemplate until an application connects to multiple databases.

  • Related