diff --git a/TimetableDesigner.Backend.Events.Providers.RabbitMQ/RabbitMQEventQueue.cs b/TimetableDesigner.Backend.Events.Providers.RabbitMQ/RabbitMQEventQueue.cs index 514360d..67521dc 100644 --- a/TimetableDesigner.Backend.Events.Providers.RabbitMQ/RabbitMQEventQueue.cs +++ b/TimetableDesigner.Backend.Events.Providers.RabbitMQ/RabbitMQEventQueue.cs @@ -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 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 Password = password, }; - Task createConnectionTask = factory.CreateConnectionAsync(); - createConnectionTask.Wait(); - services.AddSingleton(createConnectionTask.Result); + 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 createConnectionTask = factory.CreateConnectionAsync()) + { + createConnectionTask.Wait(); + connection = createConnectionTask.Result; + } + } + catch (Exception ex) + { + Thread.Sleep(retryCooldown); + retryCount++; + lastException = ex; + } + } + + if (connection is null) + { + throw lastException; + } + + services.AddSingleton(connection); services.AddSingleton(sp => new RabbitMQEventQueuePublisher(sp.GetRequiredService(), exchangeName)); services.AddSingleton(sp => new RabbitMQEventQueueSubscriber(sp.GetRequiredService(), exchangeName, queuePrefix)); }