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

com.hframework.common.springext.kafkatemplate.DynamicKafkaProducerFactory Maven / Gradle / Ivy

There is a newer version: 1.0.2
Show newest version
package com.hframework.common.springext.kafkatemplate;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.serialization.Serializer;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.Lifecycle;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 注意:DynamicKafkaTemplate与DynamicKafkaProducerFactory需要同时使用
 * Created by zhangquanhong on 2016/10/11.
 */
public class DynamicKafkaProducerFactory extends DefaultKafkaProducerFactory implements ProducerFactory, Lifecycle, DisposableBean {

    private final Map configs;

    private Serializer keySerializer;

    private Serializer valueSerializer;


    public DynamicKafkaProducerFactory(Map configs) {
        this(configs, null, null);
    }

    public DynamicKafkaProducerFactory(Map configs, Serializer keySerializer, Serializer valueSerializer) {
        super(configs, keySerializer, valueSerializer);
        this.configs = new HashMap(configs);
        this.keySerializer = keySerializer;
        this.valueSerializer = valueSerializer;
    }

    public synchronized Producer createProducer(String servers) {
        Object originServers = configs.get("bootstrap.servers");
        configs.put("bootstrap.servers", servers);
        Producer producer = createProducer();
        configs.put("bootstrap.servers", originServers);
        return producer;
    }

    protected KafkaProducer createKafkaProducer() {
        return new KafkaProducer(this.configs, this.keySerializer, this.valueSerializer);
    }

    public void setKeySerializer(Serializer keySerializer) {
        this.keySerializer = keySerializer;
        super.setKeySerializer(keySerializer);
    }

    public void setValueSerializer(Serializer valueSerializer) {
        this.valueSerializer = valueSerializer;
        super.setValueSerializer(valueSerializer);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy