public async Task SubscribeAsync(string exchange, string queue, Action <IList <IDomainEvent>, IDomainEventPublisher> action, IDomainEventPublisher domainEventPublisher, CancellationToken cancellationToken)
        {
            Uri uri = _configuration.Uri;
            IRabbitConnection rabbitConnection = null;

            try
            {
                rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false);

                await _transientFaultHandler.TryAsync(
                    c => rabbitConnection.WithModelAsync(m => SubscribeAsync(m, exchange, queue, action, domainEventPublisher, c), c),
                    Label.Named("rabbitmq-subscribe"),
                    cancellationToken)
                .ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (rabbitConnection != null)
                {
                    using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
                    {
                        rabbitConnection.Dispose();
                        _connections.Remove(uri);
                    }
                }

                _log.Error(e, "Failed to subscribe to RabbitMQ");
                throw;
            }
        }
Пример #2
0
        public async Task PublishAsync(IReadOnlyCollection <RabbitMqMessage> rabbitMqMessages, CancellationToken cancellationToken)
        {
            var uri = _configuration.Uri;
            IRabbitConnection rabbitConnection = null;

            try
            {
                rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false);

                await _transientFaultHandler.TryAsync(
                    c => rabbitConnection.WithModelAsync(m => PublishAsync(m, rabbitMqMessages), c),
                    Label.Named("rabbitmq-publish"),
                    cancellationToken)
                .ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (rabbitConnection != null)
                {
                    using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
                    {
                        rabbitConnection.Dispose();
                        _connections.Remove(uri);
                    }
                }
                _log.Error(e, "Failed to publish domain events to RabbitMQ");
                throw;
            }
        }
Пример #3
0
 public void Dispose()
 {
     if (this.Connection != null)
     {
         this.Connection.Dispose();
         this.Connection = null;
     }
 }
Пример #4
0
 public ConsumerService(ILogger <ConsumerService> logger, IEventBus eventBus, IServiceScopeFactory scopeFactory, IRabbitConnection rabbitConnection, IMessageRepository repository)
 {
     _logger           = logger;
     _eventBus         = eventBus;
     _scopeFactory     = scopeFactory;
     _rabbitConnection = rabbitConnection;
     _repository       = repository;
 }
Пример #5
0
 public void Dispose()
 {
     if (this.Connection != null)
     {
         this.Connection.Dispose();
         this.Connection = null;
     }
 }
 public EventBusSubscriber(
     IRabbitConnection rabbitConnection,
     ILogger <EventBusSubscriber> logger
     )
 {
     this.logger           = logger;
     this.rabbitConnection = rabbitConnection;
 }
Пример #7
0
        public RabbitClientBase(IRabbitConnection connection, IQueueInitialization initialization)
        {
            this.Connection = connection;
            this.Connection.Disconnected += new EventHandler<ConnectionEventArgs>(Connection_Disconnected);
            this.Connection.Connected += new EventHandler<ConnectionEventArgs>(Connection_Connected);

            if(initialization != null)
                initialization.Initialize(connection, this);
        }
Пример #8
0
 protected Subscriber(IMessageHandlerProvider messageHandlerProvider, IRabbitConnection connection, IMessageFormatter messageFormatter, Logger logger)
     : base(logger)
 {
     MessageHandlerProvider = messageHandlerProvider;
     Connection = connection;
     Connection.ConnectionMade += ConnectionConnectionMade;
     Connection.ConnectionLost += ConnectionConnectionLost;
     MessageFormatter = messageFormatter;
 }
Пример #9
0
 public RabbitForwarder(string publicationAddress, IRabbitConnection connection, IQueueInitialization initialization, ISerializer serializer)
     : base(connection, initialization)
 {
     this.PublicationAddress = PublicationAddress.Parse(publicationAddress);
     this.DefaultContentType = "application/octet-stream";
     this.DefaultContentEncoding = Encoding.UTF8;
     this.DefaultNamespace = "*";
     this.Serializer = serializer;
 }
 public EventBusDispatcher(
     IRabbitConfigurationProvider rabbitConfigurationProvider,
     IRabbitConnection rabbitConnection,
     ILogger <EventBusDispatcher> logger
     )
 {
     this.logger = logger;
     this.rabbitConfigurationProvider = rabbitConfigurationProvider;
     this.rabbitConnection            = rabbitConnection;
 }
 public EventBusRabbitMQ(IRabbitConnection persistentConnection,
                         ILifetimeScope autofac, IEventBusSubscriptionsManager subsManager, string queueName = null, int retryCount = 5)
 {
     _persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection));
     _subsManager          = subsManager ?? new InMemoryEventBusSubscriptionsManager();
     _queueName            = queueName;
     _consumerChannel      = CreateConsumerChannel();
     _autofac    = autofac;
     _retryCount = retryCount;
     _subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
 }
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Producer"/> class.
        /// </summary>
        /// <param name="endpoint">
        /// The endpoint.
        /// </param>
        /// <param name="connection">
        /// Соединение с шиной сообщений
        /// </param>
        /// <param name="label">
        /// Метка сообщения, которая будет использоваться при отправлении сообщений.
        /// </param>
        /// <param name="routeResolver">
        /// Определитель маршрутов, по которым можно отсылать и получать сообщения.
        /// </param>
        /// <param name="confirmationIsRequired">
        /// Если <c>true</c> - тогда отправитель будет ожидать подтверждения о том, что сообщение было сохранено в брокере.
        /// </param>
        public Producer(IEndpoint endpoint, IRabbitConnection connection, MessageLabel label, IRouteResolver routeResolver, bool confirmationIsRequired)
        {
            this.endpoint = endpoint;

            this.connection             = connection;
            this.BrokerUrl              = connection.ConnectionString;
            this.Label                  = label;
            this.RouteResolver          = routeResolver;
            this.ConfirmationIsRequired = confirmationIsRequired;

            this.logger = LogManager.GetLogger($"{this.GetType().FullName}({this.BrokerUrl}, {this.Label}, {this.GetHashCode()})");
        }
Пример #13
0
        private void Reconnect()
        {
            try
            {
                _connection.Dispose();
            }
            catch (Exception)
            {
                Logger.Info("Error Dispose durante la reconexion, se procede a la reconexion");
            }

            _connection = _connectionProvider.Connect();
            CreateBasicConsumer();
        }
Пример #14
0
 public EventBus(
     IRabbitConnection rabbitConnection,
     IEventBusSubscriptionsManager subsManager,
     IServiceProvider serviceProvider,
     ILogger <EventBus> logger,
     string queueName = null)
 {
     _rabbitConnection            = rabbitConnection;
     _logger                      = logger;
     _subsManager                 = subsManager;
     _serviceProvider             = serviceProvider;
     _queueName                   = queueName;
     _consumerChannel             = CreateConsumerChannel();
     _subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
 }
Пример #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Listener"/> class.
        /// </summary>
        /// <param name="busContext">
        /// The bus Context.
        /// </param>
        /// <param name="connection">
        /// Соединение с шиной сообщений
        /// </param>
        /// <param name="endpoint">
        /// Прослушиваемый порт.
        /// </param>
        /// <param name="receiverOptions">
        /// Настройки получателя.
        /// </param>
        /// <param name="validatorRegistry">
        /// Реестр механизмов проверки сообщений.
        /// </param>
        public Listener(IBusContext busContext, IRabbitConnection connection, ISubscriptionEndpoint endpoint, RabbitReceiverOptions receiverOptions, MessageValidatorRegistry validatorRegistry)
        {
            this.busContext = busContext;
            this.connection = connection;

            this.endpoint          = endpoint;
            this.validatorRegistry = validatorRegistry;

            this.ReceiverOptions = receiverOptions;
            this.BrokerUrl       = connection.ConnectionString;

            this.messageHeaderStorage = this.ReceiverOptions.GetIncomingMessageHeaderStorage().Value;

            this.logger = LogManager.GetLogger($"{this.GetType().FullName}({this.BrokerUrl}, {this.GetHashCode()})");
        }
Пример #16
0
        public async Task SubscribeAsync(string exchange, string queue,
                                         Action <IList <IDomainEvent>, IDomainEventPublisher> action,
                                         IDomainEventPublisher domainEventPublisher, CancellationToken cancellationToken)
        {
            Uri uri = _configuration.Uri;
            IRabbitConnection rabbitConnection = null;

            try
            {
                rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false);

                await rabbitConnection.WithModelAsync(model => {
                    model.ExchangeDeclare(exchange, ExchangeType.Fanout);
                    model.QueueDeclare(queue, false, false, true, null);
                    model.QueueBind(queue, exchange, "");

                    var consume       = new EventingBasicConsumer(model);
                    consume.Received += (obj, @event) => {
                        var msg         = CreateRabbitMqMessage(@event);
                        var domainEvent = _eventJsonSerializer.Deserialize(msg.Message, new Metadata(msg.Headers));

                        _dispatchToEventSubscribers.DispatchToAsynchronousSubscribersAsync(domainEvent, cancellationToken);
                    };
                    model.BasicConsume(queue, false, consume);
                    return(Task.CompletedTask);
                }, cancellationToken);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (rabbitConnection != null)
                {
                    using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false))
                    {
                        rabbitConnection.Dispose();
                        _connections.Remove(uri);
                    }
                }

                _log.Error(e, "Failed to subscribe to RabbitMQ");
                throw;
            }
        }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Producer"/> class.
        /// </summary>
        /// <param name="endpoint">
        /// The endpoint.
        /// </param>
        /// <param name="connection">
        /// Соединение с шиной сообщений
        /// </param>
        /// <param name="label">
        /// Метка сообщения, которая будет использоваться при отправлении сообщений.
        /// </param>
        /// <param name="routeResolver">
        /// Определитель маршрутов, по которым можно отсылать и получать сообщения.
        /// </param>
        /// <param name="confirmationIsRequired">
        /// Если <c>true</c> - тогда отправитель будет ожидать подтверждения о том, что сообщение было сохранено в брокере.
        /// </param>
        public Producer(IEndpoint endpoint, IRabbitConnection connection, MessageLabel label, IRouteResolver routeResolver, bool confirmationIsRequired)
        {
            this.endpoint = endpoint;

            this.Channel   = connection.OpenChannel();
            this.BrokerUrl = connection.ConnectionString;
            this.logger    = LogManager.GetLogger($"{this.GetType().FullName}(URL={this.BrokerUrl})");

            this.Label                  = label;
            this.RouteResolver          = routeResolver;
            this.ConfirmationIsRequired = confirmationIsRequired;

            if (this.ConfirmationIsRequired)
            {
                this.confirmationTracker = new DefaultPublishConfirmationTracker(this.Channel);
                this.Channel.EnablePublishConfirmation();
                this.Channel.OnConfirmation(this.confirmationTracker.HandleConfirmation);
            }
        }
Пример #18
0
        public RabbitMetricOutput(
            ILoggerAdapter <RabbitMetricOutput> logger,
            IRabbitConnection connection,
            IConfiguration configuration)
        {
            // TODO: [TESTS] (RabbitMetricOutput) Add tests
            _logger     = logger;
            _connection = connection;
            _config     = BindConfiguration(configuration);

            Enabled = _config.Enabled;
            Name    = nameof(RabbitMetricOutput);

            if (!Enabled)
            {
                return;
            }

            _connection.Configure(_config);
        }
Пример #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Listener"/> class.
        /// </summary>
        /// <param name="busContext">
        /// The bus Context.
        /// </param>
        /// <param name="connection">
        /// Соединение с шиной сообщений
        /// </param>
        /// <param name="endpoint">
        /// Прослушиваемый порт.
        /// </param>
        /// <param name="receiverOptions">
        /// Настройки получателя.
        /// </param>
        /// <param name="validatorRegistry">
        /// Реестр механизмов проверки сообщений.
        /// </param>
        public Listener(IBusContext busContext, IRabbitConnection connection, ISubscriptionEndpoint endpoint, RabbitReceiverOptions receiverOptions, MessageValidatorRegistry validatorRegistry)
        {
            this.busContext        = busContext;
            this.connection        = connection;
            this.endpoint          = endpoint;
            this.validatorRegistry = validatorRegistry;

            this.ReceiverOptions = receiverOptions;
            this.BrokerUrl       = connection.ConnectionString;
            this.logger          = LogManager.GetLogger($"{this.GetType().FullName}(URL={this.BrokerUrl})");

            this.ReceiverOptions.GetIncomingMessageHeaderStorage();
            this.messageHeaderStorage = this.ReceiverOptions.GetIncomingMessageHeaderStorage().Value;

            this.Failed += _ =>
            {
                if (this.HasFailed)
                {
                    return;
                }

                this.HasFailed = true;
            };
        }
Пример #20
0
 public Publisher(IRabbitConnection rabbitConnection, ISetting setting)
 {
     _rabbitConnection = rabbitConnection;
     _setting          = setting;
 }
Пример #21
0
        private void Reconnect()
        {
            try
            {
                _connection.Dispose();
            }
            catch (Exception)
            {
                Logger.Info("Error Dispose durante la reconexion, se procede a la reconexion");
            }

            _connection = _connectionProvider.Connect();
            CreateBasicConsumer();
        }
Пример #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RabbitWrapper"/> class.
 /// </summary>
 /// <param name="connectionProvider">The connection provider.</param>
 /// <param name="rabbitWrapperType">Type of the rabbit wrapper.</param>
 internal RabbitWrapper(IConnectionProvider<IRabbitConnection> connectionProvider, RabbitWrapperType rabbitWrapperType)
 {
     _connectionProvider = connectionProvider;
     _rabbitWrapperType = rabbitWrapperType;
     _connection = _connectionProvider.Connect();
 }
Пример #23
0
 public RabbitChannel(IRabbitConnection conn)
 {
     this.Connection = conn;
     this.Model      = conn.Connection.CreateModel();
 }
Пример #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RabbitWrapper"/> class.
 /// </summary>
 /// <param name="connectionProvider">The connection provider.</param>
 /// <param name="rabbitWrapperType">Type of the rabbit wrapper.</param>
 internal RabbitWrapper(IConnectionProvider <IRabbitConnection> connectionProvider, RabbitWrapperType rabbitWrapperType)
 {
     _connectionProvider = connectionProvider;
     _rabbitWrapperType  = rabbitWrapperType;
     _connection         = _connectionProvider.Connect();
 }
Пример #25
0
 public RabbitChannelTests()
 {
     this.serviceProvider = FakeConfig.BuildServiceProvider();
     this.connection      = new RabbitConnection(this.serviceProvider, FakeConfig.Options);
     this.channel         = new RabbitChannel(this.connection);
 }
 public MessageSubscriber(IMessageHandlerProvider messageHandlerProvider, IRabbitConnection connection, IMessageFormatter messageFormatter, Logger logger)
     : base(messageHandlerProvider, connection, messageFormatter, logger)
 {
 }
Пример #27
0
 public RabbitConsumer()
 {
     _rabbitConnection = new RabbitConnection();
 }
Пример #28
0
 public RabbitConsumer(IRabbitConnection connection)
 {
     _rabbitConnection = connection;
 }
Пример #29
0
 public RabbitEventBus(IRabbitConnection rabbitConnection)
 {
     this._rabbitConnection = rabbitConnection;
 }
 public RabbitListener(IRabbitConnection <IModel> connection)
 {
     channel       = connection.Channel;
     configuration = connection.Configuration;
 }
 public RabbitPublisher(IRabbitConnection connection)
 {
     _rabbitConnection = connection;
 }
 public RabbitPublisher()
 {
     this._rabbitConnection = new RabbitConnection();
 }
 public static IRabbitConsole GetConsole(this IRabbitConnection source)
 {
     return(new HttpBasedRabbitConsole(source.ConnectionInfo));
 }
Пример #34
0
 public RabbitListener(IRabbitConnection connection, IQueueInitialization initialization)
     : base(connection, initialization)
 {
 }
 public RabbitSender(IRabbitConnection <IModel> connection)
 {
     this.connection = connection;
 }