Compare commits
1 Commits
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Exceptions;
|
||||
|
||||
namespace TimetableDesigner.Backend.Events.Providers.RabbitMQ;
|
||||
|
||||
@@ -20,6 +21,16 @@ public class RabbitMQEventQueue : EventQueue<RabbitMQEventQueue>
|
||||
string password = connectionParameters["Password"];
|
||||
string exchangeName = connectionParameters["ExchangeName"];
|
||||
string queuePrefix = connectionParameters["QueuePrefix"];
|
||||
if (!connectionParameters.TryGetValue("Retries", out string retriesStr))
|
||||
{
|
||||
retriesStr = "0";
|
||||
}
|
||||
int retries = int.Parse(retriesStr);
|
||||
if (!connectionParameters.TryGetValue("RetryCooldown", out string retryCooldownStr))
|
||||
{
|
||||
retryCooldownStr = "1000";
|
||||
}
|
||||
int retryCooldown = int.Parse(retryCooldownStr);
|
||||
|
||||
ConnectionFactory factory = new ConnectionFactory
|
||||
{
|
||||
@@ -29,9 +40,33 @@ public class RabbitMQEventQueue : EventQueue<RabbitMQEventQueue>
|
||||
Password = password,
|
||||
};
|
||||
|
||||
Task<IConnection> createConnectionTask = factory.CreateConnectionAsync();
|
||||
IConnection? connection = null;
|
||||
int retryCount = 0;
|
||||
Exception lastException = new Exception("Cannot connect to RabbitMQ");
|
||||
while (connection is null && (retries < 0 || retryCount < retries))
|
||||
{
|
||||
try
|
||||
{
|
||||
using (Task<IConnection> createConnectionTask = factory.CreateConnectionAsync())
|
||||
{
|
||||
createConnectionTask.Wait();
|
||||
services.AddSingleton(createConnectionTask.Result);
|
||||
connection = createConnectionTask.Result;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Thread.Sleep(retryCooldown);
|
||||
retryCount++;
|
||||
lastException = ex;
|
||||
}
|
||||
}
|
||||
|
||||
if (connection is null)
|
||||
{
|
||||
throw lastException;
|
||||
}
|
||||
|
||||
services.AddSingleton(connection);
|
||||
services.AddSingleton<IEventQueuePublisher, RabbitMQEventQueuePublisher>(sp => new RabbitMQEventQueuePublisher(sp.GetRequiredService<IConnection>(), exchangeName));
|
||||
services.AddSingleton<IEventQueueSubscriber, RabbitMQEventQueueSubscriber>(sp => new RabbitMQEventQueueSubscriber(sp.GetRequiredService<IConnection>(), exchangeName, queuePrefix));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user