Search in sources :

Example 1 with Prototype

use of io.micronaut.context.annotation.Prototype in project micronaut-kafka by micronaut-projects.

the class KafkaConsumerFactory method createConsumer.

/**
 * Creates a new {@link KafkaConsumer} for the given configuration.
 *
 * @param consumerConfiguration The consumer configuration
 * @param <K> The key type
 * @param <V> The value type
 * @return The consumer
 */
@Prototype
public <K, V> Consumer<K, V> createConsumer(@Parameter AbstractKafkaConsumerConfiguration<K, V> consumerConfiguration) {
    Optional<Deserializer<K>> keyDeserializer = consumerConfiguration.getKeyDeserializer();
    Optional<Deserializer<V>> valueDeserializer = consumerConfiguration.getValueDeserializer();
    Properties config = consumerConfiguration.getConfig();
    if (keyDeserializer.isPresent() && valueDeserializer.isPresent()) {
        return new KafkaConsumer<>(config, keyDeserializer.get(), valueDeserializer.get());
    } else if (keyDeserializer.isPresent() || valueDeserializer.isPresent()) {
        throw new ConfigurationException("Both the [keyDeserializer] and [valueDeserializer] must be set when setting either");
    } else {
        return new KafkaConsumer<>(config);
    }
}
Also used : ConfigurationException(io.micronaut.context.exceptions.ConfigurationException) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) Properties(java.util.Properties) Prototype(io.micronaut.context.annotation.Prototype)

Aggregations

Prototype (io.micronaut.context.annotation.Prototype)1 ConfigurationException (io.micronaut.context.exceptions.ConfigurationException)1 Properties (java.util.Properties)1 KafkaConsumer (org.apache.kafka.clients.consumer.KafkaConsumer)1