Apache Pulsar Node js app - consumer.receive function has blocked the whole functionality

40 Views Asked by At

I am reading messages continuously. I want to close my client and consumer if no message is there to read.

The below code is working fine if there are messages to read but after reading all the messages it is blocked. consumer.receive() method has blocked the whole program.

Am I doing anything wrong?

const RECEIVE_TIMEOUT = 100; // Adjust based on your needs

while (true) {
  const msg = await consumer.receive(RECEIVE_TIMEOUT);
  if (!msg) {
    // No message received within timeout, handle empty queue scenario
  } else {
    // Process the received message
    consumer.acknowledge(msg);
  }
}
1

There are 1 best solutions below

0
Penghui Li On

I think the reader API is more suitable for this case. Here is the documentation https://pulsar.apache.org/docs/next/client-libraries-node-use/#create-a-reader

if (reader.hasNext()) {
    const msg = reader.readNext();
} else {
    reader.close();
    client.close();
}