-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathRPCServer.cs
More file actions
67 lines (57 loc) · 2.09 KB
/
RPCServer.cs
File metadata and controls
67 lines (57 loc) · 2.09 KB
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
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
const string QUEUE_NAME = "rpc_queue";
var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = await factory.CreateConnectionAsync();
using var channel = await connection.CreateChannelAsync();
await channel.QueueDeclareAsync(queue: QUEUE_NAME, durable: true, exclusive: false,
autoDelete: false, arguments: new Dictionary<string, object?> { { "x-queue-type", "quorum" } });
await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += async (object sender, BasicDeliverEventArgs ea) =>
{
AsyncEventingBasicConsumer cons = (AsyncEventingBasicConsumer)sender;
IChannel ch = cons.Channel;
string response = string.Empty;
byte[] body = ea.Body.ToArray();
IReadOnlyBasicProperties props = ea.BasicProperties;
var replyProps = new BasicProperties
{
CorrelationId = props.CorrelationId
};
try
{
var message = Encoding.UTF8.GetString(body);
int n = int.Parse(message);
Console.WriteLine($" [.] Fib({message})");
response = Fib(n).ToString();
}
catch (Exception e)
{
Console.WriteLine($" [.] {e.Message}");
response = string.Empty;
}
finally
{
var responseBytes = Encoding.UTF8.GetBytes(response);
await ch.BasicPublishAsync(exchange: string.Empty, routingKey: props.ReplyTo!,
mandatory: true, basicProperties: replyProps, body: responseBytes);
await ch.BasicAckAsync(deliveryTag: ea.DeliveryTag, multiple: false);
}
};
await channel.BasicConsumeAsync(QUEUE_NAME, false, consumer);
Console.WriteLine(" [x] Awaiting RPC requests");
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
// Assumes only valid positive integer input.
// Don't expect this one to work for big numbers,
// and it's probably the slowest recursive implementation possible.
static int Fib(int n)
{
if (n is 0 or 1)
{
return n;
}
return Fib(n - 1) + Fib(n - 2);
}