how to implement Remote procedure call (RPC) in RabbitMQ using Nodejshow to implement RPC Mechanism using RabbitMQ in javaHow can I update NodeJS and NPM to the next versions?RPC using EventMachine & RabbitMQHow to implement SSL in rabbitmq with RPC?An 8 hour RPC call using rabbitmq. It sounds crazy but is there anything wrong with it?How do I implement RPC using node to an existing RabbitMQ server with an existing exchange and queueRabbitMq Rpc: EventingBasicConsumer or QueueingBasicConsumerHow to implement RPC with RabbitMQ in Rails?RabbitMQ RPC using Node.jsYouTube API Error, Node.js
If my Scout rogue has used his full movement on his turn, can he later use the reaction from the Skirmisher feature to move again?
Did Chinese school textbook maps (c. 1951) "depict China as stretching even into the central Asian republics"?
how to remove the dotted white border around focused button text?
How do I get a European Union Pet Passport for my dog?
Is adding a new player (or players) a DM decision, or a group decision?
How can I create ribbons like these in Microsoft word 2010?
What's the point of DHS warning passengers about Manila airport?
Was touching your nose a greeting in second millenium Mesopotamia?
Intuitively, why does putting capacitors in series decrease the equivalent capacitance?
Analog is Obtuse!
Wilcoxon signed rank test – critical value for n>50
What is the line crossing the Pacific Ocean that is shown on maps?
Symbol for "not absolutely continuous" in Latex
Does the UK have a written constitution?
Why is Madam Hooch not a professor?
Avoid bfseries from bolding pm in siunitx
Should I include salary information on my CV?
What speedlites can work with the Canon EOS 4000D's non-standard hotshoe?
Do 3D printers really reach 50 micron (0.050mm) accuracy?
How can I check type T is among parameter pack Ts... in C++?
Should I hide continue button until tasks are completed?
If a high rpm motor is run at lower rpm, will it produce more torque?
Children's short story about material that accelerates away from gravity
Alphabet completion rate
how to implement Remote procedure call (RPC) in RabbitMQ using Nodejs
how to implement RPC Mechanism using RabbitMQ in javaHow can I update NodeJS and NPM to the next versions?RPC using EventMachine & RabbitMQHow to implement SSL in rabbitmq with RPC?An 8 hour RPC call using rabbitmq. It sounds crazy but is there anything wrong with it?How do I implement RPC using node to an existing RabbitMQ server with an existing exchange and queueRabbitMq Rpc: EventingBasicConsumer or QueueingBasicConsumerHow to implement RPC with RabbitMQ in Rails?RabbitMQ RPC using Node.jsYouTube API Error, Node.js
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
so i want to take a Json and parse it to Object and then implement a RPC RabbitMQ Server so that i can send the Object to the Server through RabbitMQ and there the Object will be proceed to be saved in a local Array and a universally unique id which will tell where exactly is the object stored, will be returned from that Server to the client throught the RPC.
the Official Webseite shows some Implementation to RPC in RabbitMQ, here you can find their Implementration https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html , in the Tutorial they send a Number and the Server will calculate Fibonacci Sequence and return the Result to the Client. instead i want to send an Object, not a Number and i want to receive the universally unique id(uuid) of that Object which i ll store in a global Array in my Program, i changed the code so that it ll send an Object and return the uuid but it didnt work. i ll apreciate any help from you guys
//this is my server_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
amqp.connect('here is the url: example: localhost', (err, conn) =>
conn.createChannel( (err, ch) =>
let q = 'rpc_queue';
ch.assertQueue(q, durable: false);
ch.prefetch(10);
console.log(' [x] Waiting RPC requests');
ch.consume(q, function reply(msg)
console.log("corralation key is: ", msg.properties.correlationId);
let n = uuid();
console.log(" data received ",JSON.parse(JSON.stringify(msg.content.toString())));
console.log("corralation key is: ", msg.properties.correlationId);
ch.sendToQueue(msg.properties.replyTo, Buffer.from(n.toString()), correlationId: msg.properties.correlationId);
ch.ack(msg);
);
);
);
// and this is my client_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
const express = require("express");
let data =
"name" : "hil01",
"region" : "weissach",
"ID" : "1",
"version" : "0.0.1"
amqp.connect('url: example localhost ', (err, conn) =>
conn.createChannel( (err, ch) =>
ch.assertQueue('', exclusive: true, (err, q) =>
var corr = generateUuid();
var newHil = JSON.stringify(data);
console.log(" [x] Requesting uuid for the registered HIL: ", newHil );
console.log("corralation key is: ", corr);
ch.consume(q.queue, function(msg)
if(msg.properties.correlationId == corr)
console.log(" [.] Got %s", msg.content.toString());
setTimeout(() => conn.close(); process.exit(0) , 100);
, noAck: true);
ch.sendToQueue('rpc_queue', Buffer.from(newHil, correlationId: corr, replyTo: q.queue ));
);
);
);
//method to generate the uuid, later will be replaced with the real
uuid function
var generateUuid = () => Math.random().toString() +
Math.random().toString() + Math.random().toString() ;
when i run server_rpc, [x] waiting for requests should be printed then in a seperate cmd i run client_rpc.js then the object should be sent and the server execute and return to me the uuid back to the client.
node.js rabbitmq rpc amqp
add a comment |
so i want to take a Json and parse it to Object and then implement a RPC RabbitMQ Server so that i can send the Object to the Server through RabbitMQ and there the Object will be proceed to be saved in a local Array and a universally unique id which will tell where exactly is the object stored, will be returned from that Server to the client throught the RPC.
the Official Webseite shows some Implementation to RPC in RabbitMQ, here you can find their Implementration https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html , in the Tutorial they send a Number and the Server will calculate Fibonacci Sequence and return the Result to the Client. instead i want to send an Object, not a Number and i want to receive the universally unique id(uuid) of that Object which i ll store in a global Array in my Program, i changed the code so that it ll send an Object and return the uuid but it didnt work. i ll apreciate any help from you guys
//this is my server_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
amqp.connect('here is the url: example: localhost', (err, conn) =>
conn.createChannel( (err, ch) =>
let q = 'rpc_queue';
ch.assertQueue(q, durable: false);
ch.prefetch(10);
console.log(' [x] Waiting RPC requests');
ch.consume(q, function reply(msg)
console.log("corralation key is: ", msg.properties.correlationId);
let n = uuid();
console.log(" data received ",JSON.parse(JSON.stringify(msg.content.toString())));
console.log("corralation key is: ", msg.properties.correlationId);
ch.sendToQueue(msg.properties.replyTo, Buffer.from(n.toString()), correlationId: msg.properties.correlationId);
ch.ack(msg);
);
);
);
// and this is my client_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
const express = require("express");
let data =
"name" : "hil01",
"region" : "weissach",
"ID" : "1",
"version" : "0.0.1"
amqp.connect('url: example localhost ', (err, conn) =>
conn.createChannel( (err, ch) =>
ch.assertQueue('', exclusive: true, (err, q) =>
var corr = generateUuid();
var newHil = JSON.stringify(data);
console.log(" [x] Requesting uuid for the registered HIL: ", newHil );
console.log("corralation key is: ", corr);
ch.consume(q.queue, function(msg)
if(msg.properties.correlationId == corr)
console.log(" [.] Got %s", msg.content.toString());
setTimeout(() => conn.close(); process.exit(0) , 100);
, noAck: true);
ch.sendToQueue('rpc_queue', Buffer.from(newHil, correlationId: corr, replyTo: q.queue ));
);
);
);
//method to generate the uuid, later will be replaced with the real
uuid function
var generateUuid = () => Math.random().toString() +
Math.random().toString() + Math.random().toString() ;
when i run server_rpc, [x] waiting for requests should be printed then in a seperate cmd i run client_rpc.js then the object should be sent and the server execute and return to me the uuid back to the client.
node.js rabbitmq rpc amqp
add a comment |
so i want to take a Json and parse it to Object and then implement a RPC RabbitMQ Server so that i can send the Object to the Server through RabbitMQ and there the Object will be proceed to be saved in a local Array and a universally unique id which will tell where exactly is the object stored, will be returned from that Server to the client throught the RPC.
the Official Webseite shows some Implementation to RPC in RabbitMQ, here you can find their Implementration https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html , in the Tutorial they send a Number and the Server will calculate Fibonacci Sequence and return the Result to the Client. instead i want to send an Object, not a Number and i want to receive the universally unique id(uuid) of that Object which i ll store in a global Array in my Program, i changed the code so that it ll send an Object and return the uuid but it didnt work. i ll apreciate any help from you guys
//this is my server_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
amqp.connect('here is the url: example: localhost', (err, conn) =>
conn.createChannel( (err, ch) =>
let q = 'rpc_queue';
ch.assertQueue(q, durable: false);
ch.prefetch(10);
console.log(' [x] Waiting RPC requests');
ch.consume(q, function reply(msg)
console.log("corralation key is: ", msg.properties.correlationId);
let n = uuid();
console.log(" data received ",JSON.parse(JSON.stringify(msg.content.toString())));
console.log("corralation key is: ", msg.properties.correlationId);
ch.sendToQueue(msg.properties.replyTo, Buffer.from(n.toString()), correlationId: msg.properties.correlationId);
ch.ack(msg);
);
);
);
// and this is my client_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
const express = require("express");
let data =
"name" : "hil01",
"region" : "weissach",
"ID" : "1",
"version" : "0.0.1"
amqp.connect('url: example localhost ', (err, conn) =>
conn.createChannel( (err, ch) =>
ch.assertQueue('', exclusive: true, (err, q) =>
var corr = generateUuid();
var newHil = JSON.stringify(data);
console.log(" [x] Requesting uuid for the registered HIL: ", newHil );
console.log("corralation key is: ", corr);
ch.consume(q.queue, function(msg)
if(msg.properties.correlationId == corr)
console.log(" [.] Got %s", msg.content.toString());
setTimeout(() => conn.close(); process.exit(0) , 100);
, noAck: true);
ch.sendToQueue('rpc_queue', Buffer.from(newHil, correlationId: corr, replyTo: q.queue ));
);
);
);
//method to generate the uuid, later will be replaced with the real
uuid function
var generateUuid = () => Math.random().toString() +
Math.random().toString() + Math.random().toString() ;
when i run server_rpc, [x] waiting for requests should be printed then in a seperate cmd i run client_rpc.js then the object should be sent and the server execute and return to me the uuid back to the client.
node.js rabbitmq rpc amqp
so i want to take a Json and parse it to Object and then implement a RPC RabbitMQ Server so that i can send the Object to the Server through RabbitMQ and there the Object will be proceed to be saved in a local Array and a universally unique id which will tell where exactly is the object stored, will be returned from that Server to the client throught the RPC.
the Official Webseite shows some Implementation to RPC in RabbitMQ, here you can find their Implementration https://www.rabbitmq.com/tutorials/tutorial-six-javascript.html , in the Tutorial they send a Number and the Server will calculate Fibonacci Sequence and return the Result to the Client. instead i want to send an Object, not a Number and i want to receive the universally unique id(uuid) of that Object which i ll store in a global Array in my Program, i changed the code so that it ll send an Object and return the uuid but it didnt work. i ll apreciate any help from you guys
//this is my server_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
amqp.connect('here is the url: example: localhost', (err, conn) =>
conn.createChannel( (err, ch) =>
let q = 'rpc_queue';
ch.assertQueue(q, durable: false);
ch.prefetch(10);
console.log(' [x] Waiting RPC requests');
ch.consume(q, function reply(msg)
console.log("corralation key is: ", msg.properties.correlationId);
let n = uuid();
console.log(" data received ",JSON.parse(JSON.stringify(msg.content.toString())));
console.log("corralation key is: ", msg.properties.correlationId);
ch.sendToQueue(msg.properties.replyTo, Buffer.from(n.toString()), correlationId: msg.properties.correlationId);
ch.ack(msg);
);
);
);
// and this is my client_rpc.js code :
const amqp = require('amqplib/callback_api');
const uuid = require("uuid/v1");
const express = require("express");
let data =
"name" : "hil01",
"region" : "weissach",
"ID" : "1",
"version" : "0.0.1"
amqp.connect('url: example localhost ', (err, conn) =>
conn.createChannel( (err, ch) =>
ch.assertQueue('', exclusive: true, (err, q) =>
var corr = generateUuid();
var newHil = JSON.stringify(data);
console.log(" [x] Requesting uuid for the registered HIL: ", newHil );
console.log("corralation key is: ", corr);
ch.consume(q.queue, function(msg)
if(msg.properties.correlationId == corr)
console.log(" [.] Got %s", msg.content.toString());
setTimeout(() => conn.close(); process.exit(0) , 100);
, noAck: true);
ch.sendToQueue('rpc_queue', Buffer.from(newHil, correlationId: corr, replyTo: q.queue ));
);
);
);
//method to generate the uuid, later will be replaced with the real
uuid function
var generateUuid = () => Math.random().toString() +
Math.random().toString() + Math.random().toString() ;
when i run server_rpc, [x] waiting for requests should be printed then in a seperate cmd i run client_rpc.js then the object should be sent and the server execute and return to me the uuid back to the client.
node.js rabbitmq rpc amqp
node.js rabbitmq rpc amqp
asked Mar 25 at 11:29
Nidhal BaccouriNidhal Baccouri
126 bronze badges
126 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Seems what you need here is direct reply-to RPC pattern: you want to send a message and get a response.
Here is documentation on RabbitMQ about direct reply-to: https://www.rabbitmq.com/direct-reply-to.html
TL;TR
Here is an example of a client and a server, which would work from the box:
https://github.com/Igor-lkm/node-rabbitmq-rpc-direct-reply-to
What is inside
After installation of RabbitMQ you would have 2 files to execute:
server.js
const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn)
console.log(`[ $new Date() ] Server started`);
return conn.createChannel();
)
.then(function(ch)
return ch.assertQueue(q).then(function(ok)
return ch.consume(q, function(msg)
console.log(
`[ $new Date() ] Message received: $JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)`,
);
if (msg !== null)
const response =
uuid: uuidv4(),
;
console.log(
`[ $new Date() ] Message sent: $JSON.stringify(response)`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
correlationId: msg.properties.correlationId,
,
);
ch.ack(msg);
);
);
)
.catch(console.warn);
client.js
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel =>
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg =>
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
,
noAck: true ,
);
return channel;
);
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve =>
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message),
correlationId,
replyTo: REPLY_QUEUE,
);
);
const init = async () =>
const channel = await createClient(RABBITMQ);
const message = uuid: uuid.v4() ;
console.log(`[ $new Date() ] Message sent: $JSON.stringify(message)`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ $new Date() ] Message received: $respone`);
process.exit();
;
try
init();
catch (e)
console.log(e);
You would have a result, like:
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55336811%2fhow-to-implement-remote-procedure-call-rpc-in-rabbitmq-using-nodejs%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Seems what you need here is direct reply-to RPC pattern: you want to send a message and get a response.
Here is documentation on RabbitMQ about direct reply-to: https://www.rabbitmq.com/direct-reply-to.html
TL;TR
Here is an example of a client and a server, which would work from the box:
https://github.com/Igor-lkm/node-rabbitmq-rpc-direct-reply-to
What is inside
After installation of RabbitMQ you would have 2 files to execute:
server.js
const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn)
console.log(`[ $new Date() ] Server started`);
return conn.createChannel();
)
.then(function(ch)
return ch.assertQueue(q).then(function(ok)
return ch.consume(q, function(msg)
console.log(
`[ $new Date() ] Message received: $JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)`,
);
if (msg !== null)
const response =
uuid: uuidv4(),
;
console.log(
`[ $new Date() ] Message sent: $JSON.stringify(response)`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
correlationId: msg.properties.correlationId,
,
);
ch.ack(msg);
);
);
)
.catch(console.warn);
client.js
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel =>
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg =>
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
,
noAck: true ,
);
return channel;
);
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve =>
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message),
correlationId,
replyTo: REPLY_QUEUE,
);
);
const init = async () =>
const channel = await createClient(RABBITMQ);
const message = uuid: uuid.v4() ;
console.log(`[ $new Date() ] Message sent: $JSON.stringify(message)`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ $new Date() ] Message received: $respone`);
process.exit();
;
try
init();
catch (e)
console.log(e);
You would have a result, like:
add a comment |
Seems what you need here is direct reply-to RPC pattern: you want to send a message and get a response.
Here is documentation on RabbitMQ about direct reply-to: https://www.rabbitmq.com/direct-reply-to.html
TL;TR
Here is an example of a client and a server, which would work from the box:
https://github.com/Igor-lkm/node-rabbitmq-rpc-direct-reply-to
What is inside
After installation of RabbitMQ you would have 2 files to execute:
server.js
const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn)
console.log(`[ $new Date() ] Server started`);
return conn.createChannel();
)
.then(function(ch)
return ch.assertQueue(q).then(function(ok)
return ch.consume(q, function(msg)
console.log(
`[ $new Date() ] Message received: $JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)`,
);
if (msg !== null)
const response =
uuid: uuidv4(),
;
console.log(
`[ $new Date() ] Message sent: $JSON.stringify(response)`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
correlationId: msg.properties.correlationId,
,
);
ch.ack(msg);
);
);
)
.catch(console.warn);
client.js
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel =>
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg =>
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
,
noAck: true ,
);
return channel;
);
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve =>
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message),
correlationId,
replyTo: REPLY_QUEUE,
);
);
const init = async () =>
const channel = await createClient(RABBITMQ);
const message = uuid: uuid.v4() ;
console.log(`[ $new Date() ] Message sent: $JSON.stringify(message)`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ $new Date() ] Message received: $respone`);
process.exit();
;
try
init();
catch (e)
console.log(e);
You would have a result, like:
add a comment |
Seems what you need here is direct reply-to RPC pattern: you want to send a message and get a response.
Here is documentation on RabbitMQ about direct reply-to: https://www.rabbitmq.com/direct-reply-to.html
TL;TR
Here is an example of a client and a server, which would work from the box:
https://github.com/Igor-lkm/node-rabbitmq-rpc-direct-reply-to
What is inside
After installation of RabbitMQ you would have 2 files to execute:
server.js
const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn)
console.log(`[ $new Date() ] Server started`);
return conn.createChannel();
)
.then(function(ch)
return ch.assertQueue(q).then(function(ok)
return ch.consume(q, function(msg)
console.log(
`[ $new Date() ] Message received: $JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)`,
);
if (msg !== null)
const response =
uuid: uuidv4(),
;
console.log(
`[ $new Date() ] Message sent: $JSON.stringify(response)`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
correlationId: msg.properties.correlationId,
,
);
ch.ack(msg);
);
);
)
.catch(console.warn);
client.js
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel =>
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg =>
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
,
noAck: true ,
);
return channel;
);
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve =>
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message),
correlationId,
replyTo: REPLY_QUEUE,
);
);
const init = async () =>
const channel = await createClient(RABBITMQ);
const message = uuid: uuid.v4() ;
console.log(`[ $new Date() ] Message sent: $JSON.stringify(message)`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ $new Date() ] Message received: $respone`);
process.exit();
;
try
init();
catch (e)
console.log(e);
You would have a result, like:
Seems what you need here is direct reply-to RPC pattern: you want to send a message and get a response.
Here is documentation on RabbitMQ about direct reply-to: https://www.rabbitmq.com/direct-reply-to.html
TL;TR
Here is an example of a client and a server, which would work from the box:
https://github.com/Igor-lkm/node-rabbitmq-rpc-direct-reply-to
What is inside
After installation of RabbitMQ you would have 2 files to execute:
server.js
const amqp = require('amqplib');
const uuidv4 = require('uuid/v4');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
const open = require('amqplib').connect(RABBITMQ);
const q = 'example';
// Consumer
open
.then(function(conn)
console.log(`[ $new Date() ] Server started`);
return conn.createChannel();
)
.then(function(ch)
return ch.assertQueue(q).then(function(ok)
return ch.consume(q, function(msg)
console.log(
`[ $new Date() ] Message received: $JSON.stringify(
JSON.parse(msg.content.toString('utf8')),
)`,
);
if (msg !== null)
const response =
uuid: uuidv4(),
;
console.log(
`[ $new Date() ] Message sent: $JSON.stringify(response)`,
);
ch.sendToQueue(
msg.properties.replyTo,
Buffer.from(JSON.stringify(response)),
correlationId: msg.properties.correlationId,
,
);
ch.ack(msg);
);
);
)
.catch(console.warn);
client.js
const amqp = require('amqplib');
const EventEmitter = require('events');
const uuid = require('uuid');
const RABBITMQ = 'amqp://guest:guest@localhost:5672';
// pseudo-queue for direct reply-to
const REPLY_QUEUE = 'amq.rabbitmq.reply-to';
const q = 'example';
// Credits for Event Emitter goes to https://github.com/squaremo/amqp.node/issues/259
const createClient = rabbitmqconn =>
amqp
.connect(rabbitmqconn)
.then(conn => conn.createChannel())
.then(channel =>
channel.responseEmitter = new EventEmitter();
channel.responseEmitter.setMaxListeners(0);
channel.consume(
REPLY_QUEUE,
msg =>
channel.responseEmitter.emit(
msg.properties.correlationId,
msg.content.toString('utf8'),
);
,
noAck: true ,
);
return channel;
);
const sendRPCMessage = (channel, message, rpcQueue) =>
new Promise(resolve =>
const correlationId = uuid.v4();
channel.responseEmitter.once(correlationId, resolve);
channel.sendToQueue(rpcQueue, Buffer.from(message),
correlationId,
replyTo: REPLY_QUEUE,
);
);
const init = async () =>
const channel = await createClient(RABBITMQ);
const message = uuid: uuid.v4() ;
console.log(`[ $new Date() ] Message sent: $JSON.stringify(message)`);
const respone = await sendRPCMessage(channel, JSON.stringify(message), q);
console.log(`[ $new Date() ] Message received: $respone`);
process.exit();
;
try
init();
catch (e)
console.log(e);
You would have a result, like:
answered Mar 25 at 18:32
IgorIgor
2881 gold badge3 silver badges11 bronze badges
2881 gold badge3 silver badges11 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55336811%2fhow-to-implement-remote-procedure-call-rpc-in-rabbitmq-using-nodejs%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown