/// <inheritdoc cref="IStartable.Start"/>
        public void Start()
        {
            var rabbitMqSubscriptionSettings = RabbitMqSubscriptionSettings.ForSubscriber(
                _connectionString,
                _exchangeName,
                _queueName);

            if (_isDurable)
            {
                rabbitMqSubscriptionSettings = rabbitMqSubscriptionSettings.MakeDurable();
            }

            _subscriber = new RabbitMqSubscriber <TMessage>(
                _logFactory,
                rabbitMqSubscriptionSettings,
                new ResilientErrorHandlingStrategy(
                    _logFactory,
                    rabbitMqSubscriptionSettings,
                    TimeSpan.FromSeconds(10),
                    next: new DeadQueueErrorHandlingStrategy(_logFactory, rabbitMqSubscriptionSettings)))
                          .SetMessageDeserializer(new JsonMessageDeserializer <TMessage>())
                          .SetPrefetchCount(_prefetchCount)
                          .Subscribe(ProcessMessageAsync)
                          .CreateDefaultBinding()
                          .Start();
        }
Ejemplo n.º 2
0
 public RabbitMqSubscriber(
     [NotNull] ILogger <RabbitMqSubscriber <TTopicModel> > logger,
     [NotNull] RabbitMqSubscriptionSettings settings)
 {
     _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     _settings          = settings ?? throw new ArgumentNullException(nameof(settings));
     _exchangeQueueName = _settings.GetQueueOrExchangeName();
     _middlewareQueue   = new MiddlewareQueue <TTopicModel>(settings);
 }
Ejemplo n.º 3
0
 public RabbitMqSubscriber(
     RabbitMqSubscriptionSettings settings,
     IErrorHandlingStrategy errorHandlingStrategy,
     bool submitTelemetry = true)
 {
     _settings = settings;
     _errorHandlingStrategy = errorHandlingStrategy;
     _submitTelemetry       = submitTelemetry;
     _exchangeQueueName     = _settings.GetQueueOrExchangeName();
 }
Ejemplo n.º 4
0
 protected JsonRabbitSubscriber(
     RabbitMqSubscriptionSettings settings,
     ILoggerFactory logFactory)
     : this(
         settings,
         true,
         100,
         false,
         logFactory)
 {
 }
Ejemplo n.º 5
0
 protected JsonRabbitSubscriber(
     RabbitMqSubscriptionSettings settings,
     bool isDurable,
     ushort prefetchCount,
     ILoggerFactory logFactory)
     : this(
         settings,
         isDurable,
         prefetchCount,
         false,
         logFactory)
 {
 }
Ejemplo n.º 6
0
        private void ConnectAndRead(RabbitMqSubscriptionSettings settings)
        {
            var factory = new ConnectionFactory {
                Uri = new Uri(settings.ConnectionString, UriKind.Absolute)
            };

            _log.WriteInfo(nameof(ConnectAndRead), settings.GetSubscriberName(), $"Trying to connect to {factory.Endpoint} ({_exchangeQueueName})");

            var cn = $"[Sub] {PlatformServices.Default.Application.ApplicationName} {PlatformServices.Default.Application.ApplicationVersion} to {_exchangeQueueName}";

            using (var connection = factory.CreateConnection(cn))
                using (var channel = connection.CreateModel())
                {
                    _log.WriteInfo(nameof(ConnectAndRead), settings.GetSubscriberName(), $"Connected to {factory.Endpoint} ({_exchangeQueueName})");

                    if (_prefetchCount.HasValue)
                    {
                        channel.BasicQos(0, _prefetchCount.Value, false);
                    }

                    var queueName = _messageReadStrategy.Configure(settings, channel);

                    var consumer = new QueueingBasicConsumer(channel);
                    var tag      = channel.BasicConsume(queueName, false, consumer);

                    //consumer.Received += MessageReceived;

                    while (!IsStopped())
                    {
                        if (!connection.IsOpen)
                        {
                            throw new RabbitMqBrokerException($"{settings.GetSubscriberName()}: connection to {connection.Endpoint} is closed");
                        }

                        var delivered = consumer.Queue.Dequeue(2000, out var eventArgs);

                        _reconnectionsInARowCount = 0;

                        if (delivered)
                        {
                            MessageReceived(eventArgs, channel);
                        }
                    }

                    channel.BasicCancel(tag);
                    connection.Close();
                }
        }
Ejemplo n.º 7
0
 protected JsonRabbitSubscriber(
     RabbitMqSubscriptionSettings settings,
     bool isDurable,
     ushort prefetchCount,
     bool sendTelemetry,
     ILoggerFactory logFactory)
 {
     _settings = settings ?? throw new ArgumentNullException(nameof(settings));
     if (isDurable)
     {
         _settings = _settings.MakeDurable();
     }
     _prefetchCount = prefetchCount;
     _loggerFactory = logFactory ?? throw new ArgumentNullException(nameof(logFactory));
     _sendTelemetry = sendTelemetry;
 }
Ejemplo n.º 8
0
        public RabbitMqSubscriber(
            [NotNull] ILogFactory logFactory,
            [NotNull] RabbitMqSubscriptionSettings settings,
            [NotNull] IErrorHandlingStrategy errorHandlingStrategy,
            bool submitTelemetry       = true,
            IDeduplicator deduplicator = null)
        {
            if (logFactory == null)
            {
                throw new ArgumentNullException(nameof(logFactory));
            }

            _log      = logFactory.CreateLog(this);
            _settings = settings ?? throw new ArgumentNullException(nameof(settings));
            _errorHandlingStrategy = errorHandlingStrategy ?? throw new ArgumentNullException(nameof(errorHandlingStrategy));
            _submitTelemetry       = submitTelemetry;
            _exchangeQueueName     = _settings.GetQueueOrExchangeName();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Registers type inherited from <see cref="JsonRabbitSubscriber{TMessage}"/> in Autofac container.
        /// </summary>
        /// <typeparam name="TSubscriber">Class type.</typeparam>
        /// <typeparam name="TMessage">Message type.</typeparam>
        /// <param name="builder">Autofac container builder.</param>
        /// <param name="rabbitMqConnString">Connection string to RabbitMq.</param>
        /// <param name="exchangeName">Exchange name.</param>
        /// <param name="queueName">Queu name.</param>
        public static IRegistrationBuilder <TSubscriber, ConcreteReflectionActivatorData, SingleRegistrationStyle> RegisterJsonRabbitSubscriber <TSubscriber, TMessage>(
            [NotNull] this ContainerBuilder builder,
            [NotNull] string rabbitMqConnString,
            [NotNull] string exchangeName,
            [NotNull] string queueName
            ) where TSubscriber : JsonRabbitSubscriber <TMessage>
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (string.IsNullOrWhiteSpace(rabbitMqConnString))
            {
                throw new ArgumentNullException(nameof(rabbitMqConnString));
            }

            if (string.IsNullOrWhiteSpace(exchangeName))
            {
                throw new ArgumentNullException(nameof(exchangeName));
            }

            if (string.IsNullOrWhiteSpace(queueName))
            {
                throw new ArgumentNullException(nameof(queueName));
            }

            var settings = RabbitMqSubscriptionSettings.ForSubscriber(
                rabbitMqConnString,
                exchangeName,
                queueName);

            return(builder.RegisterType <TSubscriber>()
                   .As <IStartStop>()
                   .WithParameter(TypedParameter.From(settings))
                   .SingleInstance());
        }
Ejemplo n.º 10
0
        public string Configure(RabbitMqSubscriptionSettings settings, IModel channel)
        {
            // If specified queue name is empty generate random name
            var queueName = String.IsNullOrEmpty(settings.QueueName)
                ? settings.ExchangeName + "." + Guid.NewGuid().ToString()
                : settings.QueueName;

            // For random name set autodelete
            //var autodelete = String.IsNullOrEmpty(settings.QueueName) ? true : false;

            // autodelete is always reverse from isdurable
            var autodelete = !settings.IsDurable;
            IDictionary <string, object> args = null;

            if (!string.IsNullOrEmpty(settings.DeadLetterExchangeName))
            {
                var poisonQueueName = $"{queueName}-poison";
                args = new Dictionary <string, object>
                {
                    { "x-dead-letter-exchange", settings.DeadLetterExchangeName }
                };
                channel.ExchangeDeclare(settings.DeadLetterExchangeName, "direct", durable: true);
                channel.QueueDeclare(poisonQueueName, durable: settings.IsDurable, exclusive: false, autoDelete: false);
                channel.QueueBind(poisonQueueName, settings.DeadLetterExchangeName, settings.RoutingKey ?? string.Empty);
            }

            settings.QueueName = channel.QueueDeclare(queueName, durable: settings.IsDurable, exclusive: false, autoDelete: autodelete, arguments: args).QueueName;


            channel.QueueBind(
                queue: settings.QueueName,
                exchange: settings.ExchangeName,
                routingKey: string.IsNullOrWhiteSpace(_routingKey) ? settings.RoutingKey ?? string.Empty : _routingKey);

            return(settings.QueueName);
        }
 public string Configure(RabbitMqSubscriptionSettings settings, IModel channel)
 {
     return(settings.QueueName);
 }