实现方法一:
public class ProducerInstance {
private static KafkaProducer<Integer, String> instance;
static{
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, ServerProperties.KAFKA_SERVER_IP + ":" + ServerProperties.KAFKA_SERVER_PORT);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
instance = new KafkaProducer<>(props);
}
public static KafkaProducer<Integer, String> getInstance() {
return instance;
}
}
实现方法二:
public class ProducerInstance {
private static KafkaProducer<Integer, String> instance = null;
public static Object instanceLock = new Object();
public static KafkaProducer<Integer, String> getInstance() {
if(instance == null){
synchronized (instanceLock){
if(instance == null){
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, ServerProperties.KAFKA_SERVER_IP + ":" + ServerProperties.KAFKA_SERVER_PORT);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerSerializer");
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
instance = new KafkaProducer<>(props);
}
}
}
return instance;
}
}
注意
if(instance == null){
synchronized (instanceLock){
if(instance == null){
//init instance
}
}
}
可以保证在多线程的情况下,init instance只在第一次getInstance的时候执行一遍