Search code examples
javascriptnode.jsamqpnode-amqpnode-amqplib

Why the nodejs with amqplib consume function is closure?


I use the nodejs amqplib module to connect rabbitmq. I found the consume function is become a closure function, but I couldn't understand why. I didn't use closure.

My code is below. I found the corr in the returnOK still get the first time value. When I fire this function second times. The corr still the value at first time. I think that is odd. Someone could explain this?

  const corr = new Date().getTime();
  try {
    const params = JSON.stringify(req.body);
    console.log('corr first =', corr);
    await ch.sendToQueue(q, Buffer.from(params), {
      deliveryMode: true,
      correlationId: corr.toString(),
      replyTo: queue.queue,
    });

    const returnOK = (msg) => {
      if (msg.properties.correlationId === corr.toString()) {
        console.info('******* Proxy send message done *******');
        res.status(HTTPStatus.OK).json('Done');
      }
    };
    await ch.consume(queue.queue, returnOK, { noAck: true });
  } catch (error) {
    res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json(error);
  }

Solution

  • It appears you're calling ch.consume on every request, in effect creating a new consumer every time. You should only do that once.

    What is happening is that the first consumer is picking up the messages.

    To fix this, you probably want to move ch.consume outside the request handler.