forked from dsaradini/nameko-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_rpc.js
57 lines (45 loc) · 1.83 KB
/
worker_rpc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const amqplib = require("amqplib");
const {AMQP_URL, RPC_EXCHANGE} = require("./config");
const handleServiceRpc = async (service, rpc, args, kwargs) => {
return 'node-js-' + args[0];
};
const run = async () => {
const connection = await amqplib.connect(AMQP_URL);
const channel = await connection.createChannel();
const serviceName = "service_y";
const queueName = `rpc-${serviceName}`;
await channel.assertExchange(RPC_EXCHANGE, "topic", {durable: true});
console.log("Waiting on exchange:", RPC_EXCHANGE);
const consumer = await channel.consume(queueName, async (msg) => {
if (msg !== null) {
console.log("Message.properties :", msg.properties);
console.log("Message.fields :", msg.fields);
const params = JSON.parse(msg.content.toString());
console.log("Message.content :", params);
const routingKey = msg.fields.routingKey;
const [service, rpc] = routingKey.split(".");
const {correlationId, replyTo} = msg.properties;
console.log(`Action on service '${service}' and method '${rpc}'`);
const result = await handleServiceRpc(service, rpc, params.args || [], params.kwargs || {});
const content = new Buffer(JSON.stringify({
'result': result,
}));
// publish result
await channel.publish(RPC_EXCHANGE, replyTo, content, {
correlationId,
contentType: 'application/json',
contentEncoding: 'utf-8',
});
await channel.ack(msg);
}
});
console.log("consumer", consumer);
console.log("CTRL-C to exit");
process.on('SIGINT', function() {
console.log("Interrupted by user");
connection.close();
});
};
(async function() {
await run();
})();