|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Text; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using RabbitMQ.Client; |
| 8 | + |
| 9 | +const int MESSAGE_COUNT = 50_000; |
| 10 | +bool debug = false; |
| 11 | + |
| 12 | +await PublishMessagesIndividuallyAsync(); |
| 13 | +await PublishMessagesInBatchAsync(); |
| 14 | +await HandlePublishConfirmsAsynchronously(); |
| 15 | + |
| 16 | +static Task<IConnection> CreateConnectionAsync() |
| 17 | +{ |
| 18 | + var factory = new ConnectionFactory { HostName = "localhost" }; |
| 19 | + return factory.CreateConnectionAsync(); |
| 20 | +} |
| 21 | + |
| 22 | +static async Task PublishMessagesIndividuallyAsync() |
| 23 | +{ |
| 24 | + using IConnection connection = await CreateConnectionAsync(); |
| 25 | + using IChannel channel = await connection.CreateChannelAsync(); |
| 26 | + |
| 27 | + // declare a server-named queue |
| 28 | + QueueDeclareOk queueDeclareResult = await channel.QueueDeclareAsync(); |
| 29 | + string queueName = queueDeclareResult.QueueName; |
| 30 | + await channel.ConfirmSelectAsync(); |
| 31 | + |
| 32 | + var sw = new Stopwatch(); |
| 33 | + sw.Start(); |
| 34 | + |
| 35 | + for (int i = 0; i < MESSAGE_COUNT; i++) |
| 36 | + { |
| 37 | + byte[] body = Encoding.UTF8.GetBytes(i.ToString()); |
| 38 | + await channel.BasicPublishAsync(exchange: string.Empty, routingKey: queueName, body: body); |
| 39 | + } |
| 40 | + |
| 41 | + await channel.WaitForConfirmsOrDieAsync(); |
| 42 | + |
| 43 | + sw.Stop(); |
| 44 | + |
| 45 | + Console.WriteLine($"Published {MESSAGE_COUNT:N0} messages individually in {sw.ElapsedMilliseconds:N0} ms"); |
| 46 | +} |
| 47 | + |
| 48 | +static async Task PublishMessagesInBatchAsync() |
| 49 | +{ |
| 50 | + using IConnection connection = await CreateConnectionAsync(); |
| 51 | + using IChannel channel = await connection.CreateChannelAsync(); |
| 52 | + |
| 53 | + // declare a server-named queue |
| 54 | + QueueDeclareOk queueDeclareResult = await channel.QueueDeclareAsync(); |
| 55 | + string queueName = queueDeclareResult.QueueName; |
| 56 | + await channel.ConfirmSelectAsync(); |
| 57 | + |
| 58 | + int batchSize = 100; |
| 59 | + int outstandingMessageCount = 0; |
| 60 | + |
| 61 | + var sw = new Stopwatch(); |
| 62 | + sw.Start(); |
| 63 | + |
| 64 | + var publishTasks = new List<Task>(); |
| 65 | + for (int i = 0; i < MESSAGE_COUNT; i++) |
| 66 | + { |
| 67 | + byte[] body = Encoding.UTF8.GetBytes(i.ToString()); |
| 68 | + publishTasks.Add(channel.BasicPublishAsync(exchange: string.Empty, routingKey: queueName, body: body).AsTask()); |
| 69 | + outstandingMessageCount++; |
| 70 | + |
| 71 | + if (outstandingMessageCount == batchSize) |
| 72 | + { |
| 73 | + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| 74 | + await Task.WhenAll(publishTasks).WaitAsync(cts.Token); |
| 75 | + publishTasks.Clear(); |
| 76 | + |
| 77 | + await channel.WaitForConfirmsOrDieAsync(cts.Token); |
| 78 | + outstandingMessageCount = 0; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + if (outstandingMessageCount > 0) |
| 83 | + { |
| 84 | + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| 85 | + await channel.WaitForConfirmsOrDieAsync(cts.Token); |
| 86 | + } |
| 87 | + |
| 88 | + sw.Stop(); |
| 89 | + Console.WriteLine($"Published {MESSAGE_COUNT:N0} messages in batch in {sw.ElapsedMilliseconds:N0} ms"); |
| 90 | +} |
| 91 | + |
| 92 | +async Task HandlePublishConfirmsAsynchronously() |
| 93 | +{ |
| 94 | + using IConnection connection = await CreateConnectionAsync(); |
| 95 | + using IChannel channel = await connection.CreateChannelAsync(); |
| 96 | + |
| 97 | + // declare a server-named queue |
| 98 | + QueueDeclareOk queueDeclareResult = await channel.QueueDeclareAsync(); |
| 99 | + string queueName = queueDeclareResult.QueueName; |
| 100 | + await channel.ConfirmSelectAsync(); |
| 101 | + |
| 102 | + bool publishingCompleted = false; |
| 103 | + var allMessagesConfirmedTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); |
| 104 | + var outstandingConfirms = new LinkedList<ulong>(); |
| 105 | + var semaphore = new SemaphoreSlim(1, 1); |
| 106 | + void CleanOutstandingConfirms(ulong deliveryTag, bool multiple) |
| 107 | + { |
| 108 | + if (debug) |
| 109 | + { |
| 110 | + Console.WriteLine("{0} [DEBUG] confirming message: {1} (multiple: {2})", |
| 111 | + DateTime.Now, deliveryTag, multiple); |
| 112 | + } |
| 113 | + |
| 114 | + semaphore.Wait(); |
| 115 | + try |
| 116 | + { |
| 117 | + if (multiple) |
| 118 | + { |
| 119 | + do |
| 120 | + { |
| 121 | + LinkedListNode<ulong>? node = outstandingConfirms.First; |
| 122 | + if (node is null) |
| 123 | + { |
| 124 | + break; |
| 125 | + } |
| 126 | + if (node.Value <= deliveryTag) |
| 127 | + { |
| 128 | + outstandingConfirms.RemoveFirst(); |
| 129 | + } |
| 130 | + else |
| 131 | + { |
| 132 | + break; |
| 133 | + } |
| 134 | + } while (true); |
| 135 | + } |
| 136 | + else |
| 137 | + { |
| 138 | + outstandingConfirms.Remove(deliveryTag); |
| 139 | + } |
| 140 | + } |
| 141 | + finally |
| 142 | + { |
| 143 | + semaphore.Release(); |
| 144 | + } |
| 145 | + |
| 146 | + if (publishingCompleted && outstandingConfirms.Count == 0) |
| 147 | + { |
| 148 | + allMessagesConfirmedTcs.SetResult(true); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + channel.BasicAcks += (sender, ea) => CleanOutstandingConfirms(ea.DeliveryTag, ea.Multiple); |
| 153 | + channel.BasicNacks += (sender, ea) => |
| 154 | + { |
| 155 | + Console.WriteLine($"{DateTime.Now} [WARNING] message sequence number: {ea.DeliveryTag} has been nacked (multiple: {ea.Multiple})"); |
| 156 | + CleanOutstandingConfirms(ea.DeliveryTag, ea.Multiple); |
| 157 | + }; |
| 158 | + |
| 159 | + var sw = new Stopwatch(); |
| 160 | + sw.Start(); |
| 161 | + |
| 162 | + var publishTasks = new List<Task>(); |
| 163 | + for (int i = 0; i < MESSAGE_COUNT; i++) |
| 164 | + { |
| 165 | + string msg = i.ToString(); |
| 166 | + byte[] body = Encoding.UTF8.GetBytes(msg); |
| 167 | + ulong nextPublishSeqNo = channel.NextPublishSeqNo; |
| 168 | + if ((ulong)(i + 1) != nextPublishSeqNo) |
| 169 | + { |
| 170 | + Console.WriteLine($"{DateTime.Now} [WARNING] i {i + 1} does not equal next sequence number: {nextPublishSeqNo}"); |
| 171 | + } |
| 172 | + await semaphore.WaitAsync(); |
| 173 | + try |
| 174 | + { |
| 175 | + outstandingConfirms.AddLast(nextPublishSeqNo); |
| 176 | + } |
| 177 | + finally |
| 178 | + { |
| 179 | + semaphore.Release(); |
| 180 | + } |
| 181 | + publishTasks.Add(channel.BasicPublishAsync(exchange: string.Empty, routingKey: queueName, body: body).AsTask()); |
| 182 | + } |
| 183 | + |
| 184 | + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); |
| 185 | + await Task.WhenAll(publishTasks).WaitAsync(cts.Token); |
| 186 | + publishingCompleted = true; |
| 187 | + |
| 188 | + try |
| 189 | + { |
| 190 | + await allMessagesConfirmedTcs.Task.WaitAsync(cts.Token); |
| 191 | + } |
| 192 | + catch (OperationCanceledException) |
| 193 | + { |
| 194 | + Console.Error.WriteLine("{0} [ERROR] all messages could not be published and confirmed within 10 seconds", DateTime.Now); |
| 195 | + } |
| 196 | + catch (TimeoutException) |
| 197 | + { |
| 198 | + Console.Error.WriteLine("{0} [ERROR] all messages could not be published and confirmed within 10 seconds", DateTime.Now); |
| 199 | + } |
| 200 | + |
| 201 | + sw.Stop(); |
| 202 | + Console.WriteLine($"Published {MESSAGE_COUNT:N0} messages and handled confirm asynchronously {sw.ElapsedMilliseconds:N0} ms"); |
| 203 | +} |
0 commit comments