示例#1
0
        public Tuple <INatsConnection, IList <IOp> > OpenConnection(ConnectionInfo connectionInfo, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(connectionInfo, nameof(connectionInfo));

            if (cancellationToken.IsCancellationRequested)
            {
                throw NatsException.CouldNotEstablishAnyConnection();
            }

            var hosts = new Queue <Host>(connectionInfo.Hosts.GetRandomized());

            while (!cancellationToken.IsCancellationRequested && hosts.Any())
            {
                var host = hosts.Dequeue();

                try
                {
                    return(EstablishConnection(
                               host,
                               connectionInfo,
                               cancellationToken));
                }
                catch (Exception ex)
                {
                    Logger.Error($"Error while connecting to {host}. Trying with next host (if any).", ex);
                }
            }

            throw NatsException.CouldNotEstablishAnyConnection();
        }
        public async Task <(INatsConnection connection, IList <IOp> consumedOps)> OpenConnectionAsync(
            ConnectionInfo connectionInfo,
            CancellationToken cancellationToken)
        {
            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var hosts = new Queue <Host>(connectionInfo.Hosts.GetRandomized()); //TODO: Rank

            bool ShouldTryAndConnect() => !cancellationToken.IsCancellationRequested && hosts.Any();

            while (ShouldTryAndConnect())
            {
                var host = hosts.Dequeue();

                try
                {
                    return(await EstablishConnectionAsync(
                               host,
                               connectionInfo,
                               cancellationToken).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    Logger.Error($"Error while connecting to {host}. Trying with next host (if any).", ex);

                    if (!ShouldTryAndConnect())
                    {
                        throw;
                    }
                }
            }

            throw NatsException.CouldNotEstablishAnyConnection();
        }