All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.opentable.kafka.builders.KafkaProducerBuilder Maven / Gradle / Ivy

The newest version!
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.opentable.kafka.builders;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.serialization.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Main builder for KafkaProducer. This is usually entered via a KafkaConsumerBuilderFactoryBean so some "sugar" is injected.
 * @param  Key
 * @param  Value
 */
public class KafkaProducerBuilder  extends KafkaProducerBaseBuilder, K, V> {

    private static final Logger LOG = LoggerFactory.getLogger(KafkaBaseBuilder.class);

    public KafkaProducerBuilder(EnvironmentProvider environmentProvider) {
        this(new HashMap<>(), environmentProvider);
    }

    public KafkaProducerBuilder(Map prop, EnvironmentProvider environmentProvider) {
        super(prop, environmentProvider);
    }

    @Override
    public  KafkaProducerBuilder withSerializers(Class> keySer, Class> valSer) {
        return (KafkaProducerBuilder) super.withSerializers(keySer, valSer);
    }

    @Override
    public  KafkaProducerBuilder withSerializers(Serializer keySer, Serializer valSer) {
        return (KafkaProducerBuilder) super.withSerializers(keySer, valSer);
    }

    @Override
    protected KafkaProducerBuilder self() {
        return this;
    }

    private  Producer producer(Serializer keySerializer, Serializer valueSerializer) {
        LOG.trace("Building KafkaProducer with props {}", getFinalProperties());
        if (keySerializer != null || valueSerializer != null) {
            LOG.warn("You passed an INSTANCE (as opposed to class) as a Serializer. That's fine, but realize configure() will not be called on the Serializer. That's per Kafka Design.");
        }
        return new KafkaProducer<>(getFinalProperties(), keySerializer, valueSerializer);
    }

    public Producer build() {
        internalBuild();
        return this.producer(keySerializer, valueSerializer);
    }

    public Supplier> supplier() {
        internalBuild();
        return () -> this.producer(keySerializer, valueSerializer);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy