com.hframework.common.springext.kafkatemplate.DynamicKafkaProducerFactory Maven / Gradle / Ivy
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);
}
}