Exemplo n.º 1
0
        /// <summary>
        /// Publishes an integration event using RabbitMQ basic publish
        /// Uses default retry policy configured on app
        /// </summary>
        /// <typeparam name="TEvent">IntegrationEvent</typeparam>
        /// <param name="event">Integration event to be published</param>
        public void Publish <TEvent>(TEvent @event)
            where TEvent : IntegrationEvent
        {
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            using (var channel = _connection.CreateModel())
            {
                channel.ExchangeDeclare(
                    exchange: EXCHANGE_NAME,
                    type: Enum.GetName(typeof(RabbitMQExchangeType), _exchangeType).ToLower());

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

                RabbitMQFactory.GetDefaultRetryPolicy(_logger, _retryCount)
                .Execute((Action)(() =>
                {
                    channel.BasicPublish(
                        exchange: EXCHANGE_NAME,
                        routingKey: @event.GetType().Name,
                        body: body);
                }));
            }
        }
        public bool TryConnect()
        {
            _logger.LogInformation("RabbitMQ Client is trying to connect");

            lock (sync_root)
            {
                RabbitMQFactory.GetDefaultRetryPolicy(_logger, _retryCount)
                .Execute(() => _connection = _connectionFactory.CreateConnection());

                if (IsConnected)
                {
                    _connection.ConnectionShutdown += OnConnectionShutdown;
                    _connection.CallbackException  += OnCallbackException;
                    _connection.ConnectionBlocked  += OnConnectionBlocked;

                    _logger.LogInformation($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");

                    return(true);
                }
                else
                {
                    _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened");

                    return(false);
                }
            }
        }