Пример #1
0
        public RabbitMqAgent(Uri uri)
        {
            if (uri.Scheme != "rabbitmq")
            {
                throw new ArgumentOutOfRangeException(nameof(uri), "The protocol must be 'rabbitmq'");
            }
            Uri = uri;

            ConnectionFactory.Port = uri.IsDefaultPort ? 5672 : uri.Port;


            var segments = uri.Segments.Where(x => x != "/").Select(x => x.TrimEnd('/')).ToArray();

            if (!segments.Any())
            {
                throw new ArgumentOutOfRangeException(nameof(uri), "Unable to determine the routing key / queue for the Uri " + uri);
            }

            if (segments[0] == TransportConstants.Durable)
            {
                IsDurable = uri.IsDurable();
                segments  = segments.Skip(1).ToArray();
            }

            if (!segments.Any())
            {
                throw new ArgumentOutOfRangeException(nameof(uri), "Unable to determine the routing key / queue for the Uri " + uri);
            }


            if (ExchangeType.TryParse <ExchangeType>(segments[0], out var exchangeType))
            {
                ExchangeType = exchangeType;
                segments     = segments.Skip(1).ToArray();
            }

            if (!segments.Any())
            {
                throw new ArgumentOutOfRangeException(nameof(uri), "Unable to determine the routing key / queue for the Uri " + uri);
            }


            if (segments.Length > 1)
            {
                ExchangeName = segments[0];
                QueueName    = segments.Skip(1).Join("/");
            }
            else
            {
                QueueName = segments.Single();
            }

            _connection = new Lazy <IConnection>(() => ConnectionActivator(ConnectionFactory));

            _model = new Lazy <IModel>(() =>
            {
                var channel = _connection.Value.CreateModel();
                channel.CreateBasicProperties().Persistent = IsDurable;

                if (ExchangeName.IsNotEmpty())
                {
                    channel.ExchangeDeclare(ExchangeName, ExchangeType.ToString(), IsDurable, false);
                    channel.QueueDeclare(QueueName, durable: IsDurable, autoDelete: false, exclusive: false);
                    channel.QueueBind(QueueName, ExchangeName, "");
                }
                else
                {
                    channel.QueueDeclare(QueueName, durable: IsDurable, autoDelete: false, exclusive: false);
                }

                return(channel);
            });
        }