コード例 #1
0
        public void Publish(IntegrationEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            _logger.LogTrace("Creating RabbitMQ consumer channel");

            using (var channel = _persistentConnection.CreateModel())
            {
                _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);

                channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct");

                var eventName = @event.GetType().Name;

                var message = @event.SerializeObject();

                var body = Encoding.UTF8.GetBytes(message);

                var properties = channel.CreateBasicProperties();
                properties.DeliveryMode = 2; // persistent

                _logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id);

                channel.BasicPublish(
                    exchange: BROKER_NAME,
                    routingKey: eventName,
                    mandatory: true,
                    basicProperties: properties,
                    body: body);
            }
        }
コード例 #2
0
        public void Publish <T>(T @event) where T : EventBase
        {
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            var eventType = new EventType(@event.GetType());

            _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, eventType.Name);

            _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);

            _channel = _channel ?? _connection.CreateModel();
            _channel.ExchangeDeclare(exchange: _configuration.ExchangeName, type: _exchangeType);

            var message = JsonConvert.SerializeObject(@event);
            var body    = Encoding.UTF8.GetBytes(message);

            Policy.Handle <BrokerUnreachableException>()
            .Or <SocketException>()
            .WaitAndRetry(_configuration.Retries.Publish, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
            })
            .Execute(() =>
            {
                var properties        = _channel.CreateBasicProperties();
                properties.Persistent = true;

                _logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id);

                _channel.BasicPublish(exchange: _configuration.ExchangeName, routingKey: eventType.Name, mandatory: true, basicProperties: properties, body: body);
            });
        }
        private IModel CreateConsumerChannel()
        {
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            _logger.LogTrace("Creating RabbitMQ consumer channel");

            var channel = _connection.CreateModel();

            channel.ExchangeDeclare(exchange: EVENT_BUS_BROKER_ID,
                                    type: "direct");

            channel.QueueDeclare(queue: _queueName,
                                 durable: true,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            channel.CallbackException += (sender, ea) =>
            {
                _logger.LogWarning(ea.Exception, "Recreating RabbitMQ consumer channel");

                _consumerChannel.Dispose();
                _consumerChannel = CreateConsumerChannel();
                StartConsume();
            };

            return(channel);
        }
コード例 #4
0
        public Task PublishAsync(IntegrationEvent integrationEvent)
        {
            var eventType   = integrationEvent.GetType().ToString();
            var jsonMessage = JsonConvert.SerializeObject(integrationEvent);
            var body        = Encoding.UTF8.GetBytes(jsonMessage);

            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }
            using var channel = _connection.CreateModel();

            var properties = channel.CreateBasicProperties();

            properties.DeliveryMode = 2;

            channel.BasicPublish(
                exchange: _exchangeName,
                routingKey: eventType,
                mandatory: true,
                basicProperties: properties,
                body: body);

            return(Task.CompletedTask);
        }
コード例 #5
0
 /// <summary>
 /// To open connection if it's not opened
 /// </summary>
 void OpenRabbitMQConnectionIfItIsNotOpened()
 {
     if (!_connection.IsConnected)
     {
         _connection.TryConnect();
     }
 }
コード例 #6
0
        public void Publish(IntegrationEvent @event)  //, Action<IntegrationEvent> callback=null
        {
            try
            {
                if (!_persistentConnection.IsConnected)
                {
                    _persistentConnection.TryConnect();
                }

                var policy = RetryPolicy.Handle <BrokerUnreachableException>()
                             .Or <SocketException>()
                             .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    //_logger.LogWarning(ex.ToString());
                });

                using (var channel = _persistentConnection.CreateModel())
                {
                    var eventName = @event.GetType().Name;

                    channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: "direct");

                    channel.CallbackException += (sender, ea) =>
                    {
                        //TODO: write logs for call failure here
                    };

                    channel.BasicAcks += (sender, args) =>
                    {
                        //callback?.Invoke(@event);
                    };

                    channel.BasicNacks += (sender, args) =>
                    {
                    };

                    var message = JsonConvert.SerializeObject(@event);
                    var body    = Encoding.UTF8.GetBytes(message);
                    policy.Execute(() =>
                    {
                        var properties          = channel.CreateBasicProperties();
                        properties.DeliveryMode = 2; // persistent
                        channel.ConfirmSelect();
                        channel.BasicPublish(exchange: EXCHANGE_NAME,
                                             routingKey: eventName,
                                             mandatory: true,
                                             basicProperties: properties,
                                             body: body);

                        channel.WaitForConfirmsOrDie();
                    });
                }
            }
            catch (Exception)
            {
                //TODO: log exception here
            }
        }
コード例 #7
0
        private void SubsManager_OnEventRemoved(object sender, string eventName)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            using (var channel = _persistentConnection.CreateModel())
            {
                channel.QueueUnbind(queue: _queueName,
                                    exchange: BROKER_NAME,
                                    routingKey: eventName);

                if (_subsManager.IsEmpty)
                {
                    _queueName = string.Empty;
                    _consumerChannel.Close();
                }
            }
        }
コード例 #8
0
        private void EventBusSubscribeManager_OnEventRemoved(object sender, string eventName)
        {
            if (!rabbitMQConnection.IsConnected)
            {
                rabbitMQConnection.TryConnect();
            }
            using (var channel = rabbitMQConnection.CreateModel())
            {
                channel.QueueUnbind(
                    queue: queueName,
                    exchange: BROKER_NAME,
                    routingKey: eventName,
                    arguments: null);

                if (eventBusSubscribeManager.IsEmpty)
                {
                    queueName = string.Empty;
                    consumerChannel.Close();
                }
            }
        }
コード例 #9
0
 /// <summary>
 /// To open connection if it's not opened
 /// </summary>
 void OpenRabbitMQConnectionIfItIsNotOpened()
 {
     if (!_connection.IsConnected)
     {
         try
         {
             _connection.TryConnect();
         }
         catch (Exception)
         { }
     }
 }
コード例 #10
0
        private void SubsManager_OnEventAdded(object sender, ISubscription subscription)
        {
            var type = subscription.Type;

            Task.Factory.StartNew(() =>
            {
                if (!_persistentConnection.IsConnected)
                {
                    _persistentConnection.TryConnect();
                }

                using (var channel = _persistentConnection.CreateChannel())
                {
                    channel.QueueBind(
                        queue: _queueName,
                        exchange: BROKER_NAME,
                        routingKey: _eventNameTypeResolver.GetEventName(type),
                        arguments: null
                        );
                }
            });
        }
コード例 #11
0
        private IModel CreateConsumerChannel()
        {
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            var channel = _connection.CreateModel();

            channel.QueueDeclare(
                queue: _queueName,
                durable: true,
                exclusive: false,
                autoDelete: false,
                arguments: null);

            return(channel);
        }
コード例 #12
0
        private IModel CreateChannel(Type @event)
        {
            Init(@event);
            _persistentConnection.TryConnect();

            var channel = _persistentConnection.CreateModel();

            channel.ExchangeDeclare(exchange: BROKER_NAME, type: ExchangeType.Direct);
            channel.QueueDeclare(_queueName, true, false, false, null);
            channel.QueueBind(_queueName, BROKER_NAME, _queueName, null);

            channel.CallbackException += (sender, ea) =>
            {
                _consumerChannel.Dispose();
                _consumerChannel = CreateChannel(@event);
            };

            return(channel);
        }
コード例 #13
0
 public void Publish <T>(T @event) where T : Event
 {
     try
     {
         if (!_persistentConnection.IsConnected)
         {
             _persistentConnection.TryConnect();
         }
         var policy = RetryPolicy.Handle <BrokerUnreachableException>()
                      .Or <SocketException>()
                      .WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
         {
             // _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
         });
         //var factory = new ConnectionFactory() { HostName = "rabbitmqX", Port = 5672 };
         //factory.UserName = "******";
         //factory.Password = "******";
         //factory.AutomaticRecoveryEnabled = true;
         //factory.TopologyRecoveryEnabled = true;
         //factory.NetworkRecoveryInterval = TimeSpan.FromSeconds(5);
         //factory.UseBackgroundThreadsForIO = true;
         //factory.RequestedHeartbeat = 2;
         // using (var connection = factory.CreateConnection())
         using (var channel = _persistentConnection.CreateModel())
         {
             policy.Execute(() =>
             {
                 var eventName = @event.GetType().Name;
                 channel.QueueDeclare(eventName, false, false, false, null);
                 var message = JsonConvert.SerializeObject(@event);
                 byte[] body = Encoding.UTF8.GetBytes(message);
                 channel.BasicPublish("", eventName, null, body);
             }
                            );
         }
         Console.WriteLine("publish");
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error : " + ex.Message);
     }
 }
コード例 #14
0
        public RabbitMQEventPublisher(
            IRabbitMQConnection connection,
            ILogger <RabbitMQEventPublisher> logger,
            string exchangeName,
            string queueName = null)
        {
            _connection   = connection ?? throw new ArgumentNullException(nameof(connection));
            _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
            _exchangeName = exchangeName;

            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }
            using var channel = _connection.CreateModel();

            // create exchange
            channel.ExchangeDeclare(
                exchange: _exchangeName,
                type: "topic");

            // create queue and bind to exchange if necessary
            if (!string.IsNullOrWhiteSpace(queueName))
            {
                channel.QueueDeclare(
                    queue: queueName,
                    durable: true,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null);

                channel.QueueBind(
                    queue: queueName,
                    exchange: exchangeName,
                    routingKey: "#",
                    arguments: null
                    );
            }
        }