forked from dsaradini/nameko-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker_events.js
74 lines (59 loc) · 2.28 KB
/
worker_events.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const amqplib = require("amqplib");
const uuid = require("uuid");
const {AMQP_URL} = require("./config");
// defines service types
const SERVICE_POOL = "service_pool";
const SINGLETON = "singleton";
const BROADCAST = "broadcast";
function buildQueueName(eventType, sourceServiceName, eventName, serviceName, methodName) {
if (eventType === SERVICE_POOL) {
return `evt-${sourceServiceName}-${eventName}--${serviceName}.${methodName}`;
} else if (eventType === SINGLETON) {
return `evt-${sourceServiceName}-${eventName}`;
} else if (eventType === BROADCAST) {
const broadcastId = uuid.v4();
return `evt-${sourceServiceName}-${eventName}--${serviceName}.${methodName}-${broadcastId}`;
} else {
throw Error(`Unknown event type '${eventType}'`);
}
}
const run = async () => {
const connection = await amqplib.connect(AMQP_URL);
const channel = await connection.createChannel();
const eventName = "spam";
const methodName = "node_spam";
const sourceServiceName = "service_x";
const serviceName = "service_node";
const exchangeName = `${sourceServiceName}.events`;
const eventType = BROADCAST;
await channel.assertExchange(exchangeName, "topic", {
durable: true,
autoDelete: true,
});
// check : https://github.com/nameko/nameko/blob/master/nameko/events.py#L224
const eventQueue = buildQueueName(eventType, sourceServiceName, eventName, serviceName, methodName);
await channel.assertQueue(eventQueue, {
durable: true,
autoDelete: true,
});
await channel.bindQueue(eventQueue, exchangeName, eventName);
console.log("Waiting on exchange:", exchangeName);
const consumer = await channel.consume(eventQueue, async (msg) => {
if (msg !== null) {
console.log("Message.properties :", msg.properties);
console.log("Message.fields :", msg.fields);
const params = msg.content.toString();
console.log("Message.content :", params);
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();
})();