How to check if kafka producer is connected in kafkajs

130 Views Asked by At

I have a nodejs service that handels https requests that is served in a AWS lambda function.
I'm using KafkaJs in my service and I initialize the producer in the container level.
I don't want to initialize and connect the producer each time a request is received, instead, I want to do that once in the container level and only if the producer isn't connected I want to connect it again, for that, I need to know if the producer is connected and that's what I'm trying to figure. This is part of my code:

const kafka = new Kafka(kafkaConfig);
const producer = kafka.producer();

const connectProducer = async () => {
  if (!producer._isConnected) {
    logging.log("Connecting a kafka producer");
    await producer.connect();
    logging.log("Kafka producer connected successfully");
  }
};

const sendMessageToKafka = async (message, topic_name) => {
  try {
    await connectProducer();
    logging.log("Sending a message to Kafka");
    await producer.send({
      topic: topic_name,
      messages: [message],
      timeout: 30000
    });
    logging.log("Finished sending message to Kafka");
  }
  catch (error) {
    throw logging.createError(error, "Failed to send message to Kafka", 503);
  }
};

producer._isConnected always returns undefiend, I tried also producer.isConnected() but it's not a function in kafkaJs.
I did a search over the internet without any reference.

0

There are 0 best solutions below