-
Notifications
You must be signed in to change notification settings - Fork 10
/
amqp-rpc-with-tmp-queue.js
83 lines (62 loc) · 2.25 KB
/
amqp-rpc-with-tmp-queue.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
75
76
77
78
79
80
81
82
/* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
const amqplib = require('amqplib');
const {AMQPRPCClient, AMQPRPCServer} = require('..');
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
})
}
/**
*
* @return {Promise<String>} queueName when server listens on for requests
*/
async function initServer() {
console.log('Server starting');
const connection = await amqplib.connect('amqp://localhost');
const server = new AMQPRPCServer(connection);
server.addCommand('hello', (name) => ({message: `Hello, ${name}!`}));
server.addCommand('get-time', () => ({time: new Date()}));
await server.start();
console.log('Server is ready');
return server.requestsQueue;
}
/**
*
* @param requestsQueue
* @return {Promise<void>}
*/
async function initClient1(requestsQueue) {
console.log('Tom starting');
const connection = await amqplib.connect('amqp://localhost');
const client = new AMQPRPCClient(connection, {requestsQueue});
await client.start();
const response1 = await client.sendCommand('hello', ['Tom']);
console.log(`Tom got hello response ${response1.message}`);
await delay(100);
const response2 = await client.sendCommand('get-time', []);
console.log(`Tom got 1st response for get-time: ${response2.time}`);
await delay(100);
const response3 = await client.sendCommand('get-time', []);
console.log(`Tom got 2nd response for get-time: ${response3.time}`);
}
async function initClient2(requestsQueue) {
console.log('Alisa starting');
const connection = await amqplib.connect('amqp://localhost');
const client = new AMQPRPCClient(connection, {requestsQueue});
await client.start();
const response1 = await client.sendCommand('hello', ['Alisa']);
console.log(`Alisa got hello response ${response1.message}`);
await delay(150);
const response2 = await client.sendCommand('get-time', []);
console.log(`Alisa got response for get-time: ${response2.time}`);
}
(async function main() {
console.info('\n launch server:\n');
const tmpQueueName = await initServer();
console.info('\n launch clients:\n');
await Promise.all([
initClient1(tmpQueueName),
initClient2(tmpQueueName)
]);
})().catch(console.error.bind(console, 'General error:'));