0

I have multiple node.js modules running i want to send request to some particular module to trigger some of it's function and return back response. I want to use RabbitMQ for this, but not sure how to achieve this when there are multiple modules

// Client
const amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(error0, connection) {
    connection.createChannel(function(error1, channel) {
        channel.assertQueue('', { exclusive: true }, function(error2, q) {
            const correlationId = generateUuid();
            const sendToQueue = 'rpc_queue';
            const message = JSON.stringify({ nReqCode: 123, instMsg: 'Hello!' });

            channel.consume(q.queue, function(msg) {
                if (msg.properties.correlationId == correlationId) {
                    console.log(' [.] Got %s', msg.content.toString());
                }
            }, { noAck: true });

            channel.sendToQueue(sendToQueue, Buffer.from(message), { correlationId: correlationId, replyTo: q.queue });
        });
    });
});

function generateUuid() {
    return Math.random().toString() +
           Math.random().toString() +
           Math.random().toString();
}

// Server
const amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(error0, connection) {
    connection.createChannel(function(error1, channel) {
        const queue = 'rpc_queue';

        channel.assertQueue(queue, { durable: false });
        channel.prefetch(1);
        console.log(' [x] Awaiting RPC requests');

        channel.consume(queue, function reply(msg) {
            const message = JSON.parse(msg.content.toString());

            // Process the message here
            const result = processMessage(message);

            channel.sendToQueue(msg.properties.replyTo, Buffer.from(result.toString()), { correlationId: msg.properties.correlationId });
            channel.ack(msg);
        });
    });
});

function processMessage(message) {
    // Process the message and return the result
    return 'Processed ' + message.instMsg;
}

I want to know how to communicate between multiple process using RabbitMQ in (Request/Response) format.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.