简体   繁体   中英

Kafka consumer client creation singleton instance vs static method

Please tell which one is the best practice to create Kafka consumer client.

public class KafkaConsumerFactory {

public static createKafKafkaConsumer(){
       KafkaConsumer consumer = new KafkaConsumer<   (getKafkaConsumerProperties());
      consumer.subscribe(Collections.Singleton.(getTopic()));
      return consumer;
}

Or

public class KafkaConsumerFactory {

private static KafkaConsumer consumer;  

@Synchronized
public static KafkaConsumer createKafKafkaConsumer(){

if(consumer = null)
    {
      consumer = new KafkaConsumer< (getKafkaConsumerProperties());
      consumer.subscribe(Collections.Singleton.(getTopic()));
    }

 return consumer;
}
}

Will there be any considerable benefit in having singleton Kafka consumer client in production environment ?

Kafka Consumer is not thread safe so it shouldn't be a Singleton. But in case of Producer, as it is thread safe and is recommended to have single instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM