forked from rabbitmq/rabbitmq-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_client.dart
80 lines (74 loc) · 2.41 KB
/
rpc_client.dart
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
import "dart:io";
import "dart:async";
import "dart:math";
import "package:dart_amqp/dart_amqp.dart";
var UUID = () => "${(new Random()).nextDouble()}";
class RPCClient {
Client client;
String queueTag;
String _replyQueueTag;
Completer contextChannel;
Map<String, Completer> _channels = new Map<String, Completer>();
Queue _queue;
RPCClient() : client = new Client(),
queueTag = "rpc_queue" {
contextChannel = new Completer();
client
.channel()
.then((Channel channel) => channel.queue(queueTag))
.then((Queue rpcQueue) {
_queue = rpcQueue;
return rpcQueue.channel.privateQueue();
})
.then((Queue rpcQueue) {
rpcQueue.consume(noAck: true)
.then((Consumer consumer) {
_replyQueueTag = consumer.queue.name;
consumer.listen(handler);
contextChannel.complete();
});
});
}
void handler (AmqpMessage event) {
if (!_channels
.containsKey(
event.properties.corellationId)) return;
print(" [.] Got ${event.payloadAsString}");
_channels
.remove(event.properties.corellationId)
.complete(event.payloadAsString);
}
Future<String> call(int n) {
return contextChannel.future
.then((_) {
String uuid = UUID();
Completer<String> channel = new Completer<String>();
MessageProperties properties = new MessageProperties()
..replyTo = _replyQueueTag
..corellationId = uuid;
_channels[uuid] = channel;
print(" [x] Requesting ${n}");
_queue.publish({"n": n}, properties: properties);
return channel.future;
});
}
Future close() {
_channels.forEach((_, var next) => next.complete("RPC client closed"));
_channels.clear();
client.close();
}
}
void main(List<String> arguments) {
if (arguments.isEmpty) {
print("Usage: rpc_client.dart num");
return;
}
RPCClient client = new RPCClient();
int n = arguments.isEmpty ? 30 : num.parse(arguments[0]);
client.call(n)
.then((String res) {
print(" [x] fib(${n}) = ${res}");
})
.then((_) => client.close())
.then((_) => null);
}