title
stringlengths
3
46
content
stringlengths
0
1.6k
21:725
connection.Dispose();
21:726
channel = null;
21:727
connection = null;
21:728
throw;
21:729
}
21:730
21:731
If there are no valid connections or channels, they are created. channel.ConfirmSelect() declares that we need confirmation that the message was safely received and stored on disk. In the case that an exception is thrown, both the channel and the connection are disposed of, since they might have been corrupted by the exception. This way, the next communication attempt will use fresh communication and a new channel. After the disposal, the exception is rethrown so it can be handled by the Polly policy.
21:732
Finally, here are the actual communication steps:
21:733
21:734
First of all, if the queue doesn’t already exist, it is created. The queue is created as durable; that is, it must be stored on disk and not be exclusive so that several servers can extract messages from the queue in parallel:
21:735
channel.QueueDeclare(queue: `purchase_queue`,
21:736
durable: true,
21:737
exclusive: false,
21:738
autoDelete: false,
21:739
arguments: null);
21:740
21:741
21:742
Then, each message is declared as persistent; that is, it must be stored on disk:
21:743
var properties = channel.CreateBasicProperties();
21:744
properties.Persistent = true;
21:745
21:746
21:747
Finally, the message is sent through the default exchange, which sends it to a specific named queue:
21:748
channel.BasicPublish(exchange: ``,
21:749
routingKey: `purchase_queue`,
21:750
basicProperties: properties,
21:751
body: body);
21:752
21:753
21:754
As a final step, we wait until the message is safely stored on disk:
21:755
channel.WaitForConfirmsOrDie(new TimeSpan(0, 0, 5));
21:756
21:757
21:758
21:759
If a confirmation doesn’t arrive within the specified timeout, an exception is thrown that triggers the Polly retry policy. When messages are taken from a local database queue, we can also use a non-blocking confirmation that triggers the removal of the message from the local queue.
21:760
The ExecuteAsync method of the server-hosted process is defined in the HostedServices/ProcessPurchase.cs file:
21:761
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
21:762
{
21:763
while (!stoppingToken.IsCancellationRequested)
21:764
{
21:765
try
21:766
{
21:767
var factory = new ConnectionFactory() { HostName = `localhost` };
21:768
using (var connection = factory.CreateConnection())
21:769
using (var channel = connection.CreateModel())
21:770
{
21:771
channel.QueueDeclare(queue: `purchase_queue`,
21:772
durable: true,
21:773
exclusive: false,
21:774
autoDelete: false,
21:775
arguments: null);
21:776
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
21:777
var consumer = new EventingBasicConsumer(channel);
21:778
consumer.Received += async (sender, ea) =>
21:779
{
21:780
// Message received even handler
21:781
...
21:782
};
21:783
channel.BasicConsume(queue: `purchase_queue`,
21:784
autoAck: false,
21:785
consumer: consumer);
21:786
await Task.Delay(1000, stoppingToken);
21:787
}
21:788
}
21:789
catch { }
21:790
}
21:791
}
21:792
21:793
Inside the main loop, if an exception is thrown, it is intercepted by the empty catch. Since the two using statements are left, both the connection and channel are disposed of. Therefore, after the exception, a new loop is executed that creates a new fresh connection and a new channel.
21:794
In the using statement body, we ensure that our queue exists, and then set prefetch to 1. This means that each server must extract just one message at a time, which ensures a fair distribution of the load among all servers. However, setting prefetch to 1 might not be convenient when servers are based on several parallel threads since it sacrifices thread usage optimization in favor of fair distribution among servers. As a consequence, threads that could successfully process further messages (after the first) might remain idle.
21:795
Then, we define a message received event handler. BasicConsume starts the actual message reception. With autoAck set to false, when a message is read from the queue, it is not removed but just blocked so it is not available to other servers that read from the same queue. The message is actually removed when a confirmation that it has been successfully processed is sent to RabbitMQ. We can also send a failure confirmation, in which case, the message is unblocked and becomes available for processing again.
21:796
If no confirmation is received, the message remains blocked till the connection and channel are disposed of.
21:797
BasicConsume is non-blocking, so the Task.Delay after it blocks till the cancelation token is signaled. In any case, after 1 second, Task.Delay unblocks and both the connection and the channel are replaced with fresh ones. This prevents non-confirmed messages from remaining blocked forever.
21:798
Let’s move on to the code inside the message received event. This is the place where the actual message processing takes place.
21:799
As a first step, the code verifies if the application is being shut down, in which case it disposes of the channel and connection and returns without performing any further operations:
21:800
if (stoppingToken.IsCancellationRequested)
21:801
{
21:802
channel.Close();
21:803
connection.Close();
21:804
return;
21:805
}
21:806
21:807
Then, a session scope is created to access all session-scoped dependency injection services:
21:808
using (var scope = services.CreateScope())
21:809
{
21:810
try
21:811
{
21:812
// actual message processing
21:813
...
21:814
}
21:815
catch {
21:816
((EventingBasicConsumer)sender).Model.BasicNack(ea.DeliveryTag, false, true);
21:817
}
21:818
}
21:819
21:820
When an exception is thrown during the message processing, a Nack message is sent to RabbitMQ to inform it that the message processing failed. ea.DeliveryTag is a tag that uniquely identifies the message. The second argument set to false informs RabbitMQ that the Nack is just for the message identified by ea.DeliveryTag that doesn’t also involve all other messages waiting for confirmation from this server. Finally, the last argument set to true asks RabbitMQ to requeue the message whose processing failed.
21:821
Inside the try block, we get an instance of IDayStatistics:
21:822
IDayStatistics statistics = scope.ServiceProvider
21:823
.GetRequiredService<IDayStatistics>();
21:824