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

cn.geektool.kafka.producer.process.DefaultKafkaProducer Maven / Gradle / Ivy

The newest version!
package cn.geektool.kafka.producer.process;

import cn.geektool.kafka.admin.event.KafkaEvent;
import org.apache.kafka.clients.producer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.geektool.core.observer.AbstractObServer;
import cn.geektool.kafka.admin.external.IKafkaProducer;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Future;

/**
 * Kafka生产者
 *
 * @author jiangdi
 * @since 0.0.1
 */
public class DefaultKafkaProducer extends AbstractObServer implements IKafkaProducer {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * kafka producer
     */
    private Producer producer;

    /**
     * kafka producer properties
     */
    private Properties prop = new Properties();

    @Override
    public Future send(String topic, K key, V value) {
        if(logger.isDebugEnabled()){
            logger.debug("正在发送kafka数据-->topic:{},key:{},value:{}", topic, key, value);
        }
        return producer.send(new ProducerRecord<>(topic, key, value));
    }

    @Override
    public Future send(String topic, K key, V value, Callback callBack) {
        if(logger.isDebugEnabled()){
            logger.debug("正在发送kafka数据-->topic:{},key:{},value:{}", topic, key, value);
        }
        return producer.send(new ProducerRecord<>(topic, key, value), callBack);
    }

    @Override
    public Future send(ProducerRecord record) {
        return producer.send(record);
    }

    @Override
    public Future send(ProducerRecord record, Callback callBack) {
        return producer.send(record, callBack);
    }

    @Override
    public void setProperty(String key, Object value) {
        this.prop.put(key, value);
        this.refresh();
    }

    @Override
    public void setProperty(Map map) {
        this.prop.putAll(map);
        this.refresh();
    }


    /**
     * refresh producer config
     */
    private void refresh() {
        this.producer = new KafkaProducer<>(prop);
    }

    final String ACTION = "action";

    /**
     * 观察者发现数据变化执行
     */
    @Override
    protected void execute() {
        if (KafkaEvent.CREATE.equals(super.data.getOrDefault(ACTION, KafkaEvent.CREATE))) {
            this.prop.putAll(super.data);
            this.refresh();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy