-
Notifications
You must be signed in to change notification settings - Fork 10
/
amqp-rpc-with-permanent-queue.js
97 lines (74 loc) · 2.6 KB
/
amqp-rpc-with-permanent-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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* 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 initialSetup(queueName) {
const connection = await amqplib.connect('amqp://localhost');
const channel = await connection.createChannel();
await channel.assertQueue(queueName);
}
/**
*
* @param requestsQueue
* @return {Promise<void>}
*/
async function initServer(requestsQueue) {
console.log('Server starting');
const connection = await amqplib.connect('amqp://localhost');
const server = new AMQPRPCServer(connection, {requestsQueue});
server.addCommand('hello', (name) => ({message: `Hello, ${name}!`}));
server.addCommand('get-time', () => ({time: new Date()}));
await server.start();
console.log('Server is ready');
}
/**
*
* @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 setup\n');
const queueName = 'predefined-queue-name';
await initialSetup(queueName);
console.info('\n launch server:\n');
await initServer(queueName);
console.info('\n launch clients:\n');
await Promise.all([
initClient1(queueName),
initClient2(queueName)
]);
})().catch(console.error.bind(console, 'General error:'));