Ejemplo n.º 1
0
        ///<summary>
        /// Wait for RabbitMQ to start up
        ///</summary>
        public static async Task WaitForRabbitMQ(CancellationToken stoppingToken = new CancellationToken())
        {
            using var client = new TcpClient();

            Log.Information("Waiting for RabbitMQ");

            int attempt = 0;
            var random  = new Random();

            while (true)
            {
                try
                {
                    ++attempt;
                    var source = new CancellationTokenSource(5000);
                    using var linked = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken, source.Token);
                    await client.ConnectAsync(Constants.RabbitHost, Constants.RabbitPort, linked.Token);

                    break;
                }
                catch
                {
                    await random.WaitForExponentialDelay(attempt - 1, stoppingToken);

                    // We have waited long enough
                    if (attempt > 6)
                    {
                        Log.Fatal("Unable to connect to {Host}:{Port}", Constants.RabbitHost, Constants.RabbitPort);
                        throw new InvalidOperationException($"Unable to connect to {Constants.RabbitHost}:{Constants.RabbitPort}");
                    }
                }
            }

            Log.Information("RabbitMQ should be up!");
        }
Ejemplo n.º 2
0
        public async Task TryConnect(string uriString, string exchangeName, string routingKey, CancellationToken stoppingToken)
        {
            var random = new Random();

            int attempt = 0;

            while (!IsConnected)
            {
                try
                {
                    ++attempt;
                    Connect(uriString, exchangeName, routingKey);
                    break;
                }
                catch
                {
                    logger.LogInformation("Waiting for {Duration}", Constants.DelayBetweenConnectionAttempts);
                    await random.WaitForExponentialDelay(attempt - 1, stoppingToken);
                }
            }
        }