protected override async Task OnListenerTaskStartAsync(CancellationToken token)
        {
            _token    = token;
            _receiver = new RabbitMQueue(Connection);
            _receiver.EnsureConnection();
            _receiver.EnsureQueue();
            _receiverConsumer           = new EventingBasicConsumer(_receiver.Channel);
            _receiverConsumer.Received += (ch, ea) =>
            {
                var message = new RabbitMessage
                {
                    CorrelationId = Guid.Parse(ea.BasicProperties.CorrelationId),
                    Properties    = ea.BasicProperties,
                    Body          = ea.Body
                };
                Task.Run(() => EnqueueMessageToProcessAsync(ProcessingTaskAsync, message));
                _receiver.Channel.BasicAck(ea.DeliveryTag, false);
            };
            _receiverConsumerTag = _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer);
            _monitorTask         = Task.Run(MonitorProcess, _token);

            await token.WhenCanceledAsync().ConfigureAwait(false);

            if (_receiverConsumerTag != null)
            {
                _receiver.Channel.BasicCancel(_receiverConsumerTag);
            }
            _receiver.Close();

            await _monitorTask.ConfigureAwait(false);
        }
Esempio n. 2
0
        /// <inheritdoc />
        /// <summary>
        /// Delete a message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue was deleted; otherwise, false.</returns>
        public bool Delete(MQConnection queue)
        {
            var rabbitQueue = new RabbitMQueue(queue);

            rabbitQueue.EnsureConnection();
            rabbitQueue.Channel.QueueDelete(queue.Name, false, false);
            rabbitQueue.Close();
            return(true);
        }
Esempio n. 3
0
        /// <inheritdoc />
        /// <summary>
        /// Purge all messages from a message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        public void Purge(MQConnection queue)
        {
            if (!Exist(queue))
            {
                return;
            }
            var rabbitQueue = new RabbitMQueue(queue);

            rabbitQueue.EnsureConnection();
            rabbitQueue.Channel.QueuePurge(queue.Name);
            rabbitQueue.Close();
        }
Esempio n. 4
0
        /// <inheritdoc />
        /// <summary>
        /// Check if the message queue exists
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue exists; otherwise, false.</returns>
        public bool Exist(MQConnection queue)
        {
            var rabbitQueue = new RabbitMQueue(queue);

            rabbitQueue.EnsureConnection();
            try
            {
                var result = rabbitQueue.Channel.QueueDeclarePassive(queue.Name);
                rabbitQueue.Close();
                return(result != null);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 5
0
        /// <inheritdoc />
        /// <summary>
        /// Create a new message queue
        /// </summary>
        /// <param name="queue">Message Queue connection instance</param>
        /// <returns>true if the message queue was created; otherwise, false.</returns>
        public bool Create(MQConnection queue)
        {
            if (Exist(queue))
            {
                return(false);
            }
            var rabbitQueue = new RabbitMQueue(queue);

            if (!rabbitQueue.EnsureConnection())
            {
                return(false);
            }
            rabbitQueue.EnsureQueue();
            rabbitQueue.EnsureExchange();
            rabbitQueue.Close();
            return(true);
        }
Esempio n. 6
0
        /// <inheritdoc />
        /// <summary>
        /// On Send message data
        /// </summary>
        /// <param name="message">Response message instance</param>
        /// <param name="e">Event Args</param>
        protected override Task <int> OnSendAsync(ResponseMessage message, RequestReceivedEventArgs e)
        {
            if (e.ResponseQueues?.Any() != true)
            {
                return(TaskHelper.CompleteValueMinus1);
            }

            var correlationId = message.CorrelationId.ToString();
            var data          = SenderSerializer.Serialize(message);
            var response      = true;

            foreach (var queue in e.ResponseQueues)
            {
                try
                {
                    var rabbitQueue = _rQueue.GetOrAdd(queue.Route, q =>
                    {
                        var rq = new RabbitMQueue(queue);
                        rq.EnsureConnection();
                        return(rq);
                    });
                    if (!rabbitQueue.EnsureConnection())
                    {
                        continue;
                    }
                    rabbitQueue.EnsureExchange();
                    var props = rabbitQueue.Channel.CreateBasicProperties();
                    props.CorrelationId = correlationId;
                    props.Priority      = _priority;
                    props.Expiration    = _expiration;
                    props.AppId         = Core.ApplicationName;
                    props.ContentType   = SenderSerializer.MimeTypes[0];
                    props.DeliveryMode  = _deliveryMode;
                    props.Type          = _label;
                    Core.Log.LibVerbose("Sending {0} bytes to the Queue '{1}' with CorrelationId={2}", data.Count, rabbitQueue.Route + "/" + queue.Name, correlationId);
                    rabbitQueue.Channel.BasicPublish(rabbitQueue.ExchangeName ?? string.Empty, queue.Name, props, (byte[])data);
                }
                catch (Exception ex)
                {
                    response = false;
                    Core.Log.Write(ex);
                }
            }
            return(response ? Task.FromResult(data.Count) : TaskHelper.CompleteValueMinus1);
        }
Esempio n. 7
0
        private void CreateReceiverConsumer()
        {
            if (_receiverConsumer != null)
            {
                return;
            }
            if (_receiver == null)
            {
                return;
            }
            lock (_receiver)
            {
                if (_receiverConsumer != null)
                {
                    return;
                }
                if (_receiver == null)
                {
                    return;
                }
                _receiver.EnsureConnection();
                _receiver.EnsureQueue();
                _receiverConsumer           = new EventingBasicConsumer(_receiver.Channel);
                _receiverConsumer.Received += (ch, ea) =>
                {
                    var correlationId = Guid.Parse(ea.BasicProperties.CorrelationId);

                    if (!ReceivedMessages.TryRemove(correlationId, out var message))
                    {
                        _receiver.Channel.BasicNack(ea.DeliveryTag, false, true);
                        return;
                    }

                    message.CorrelationId = correlationId;
                    message.Body          = ea.Body;
                    message.Properties    = ea.BasicProperties;
                    message.WaitHandler.Set();
                    _receiver.Channel.BasicAck(ea.DeliveryTag, false);
                };
                _receiverConsumerTag =
                    _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer);
                Core.Log.LibVerbose("The Receiver for the queue \"{0}\" has been created.", _receiver.Name);
            }
        }
Esempio n. 8
0
        /// <inheritdoc />
        /// <summary>
        /// On Send message data
        /// </summary>
        /// <param name="message">Response message instance</param>
        /// <param name="e">RawRequest received event args</param>
        protected override Task <int> OnSendAsync(SubArray <byte> message, RawRequestReceivedEventArgs e)
        {
            var queues = e.ResponseQueues;

            queues.Add(new MQConnection
            {
                Route      = e.Sender.Route,
                Parameters = e.Sender.Parameters
            });

            var crId    = e.CorrelationId.ToString();
            var replyTo = e.Metadata["ReplyTo"];

            var response = true;

            foreach (var queue in queues)
            {
                try
                {
                    var rabbitQueue = _rQueue.GetOrAdd(queue.Route, q =>
                    {
                        var rq = new RabbitMQueue(queue);
                        rq.EnsureConnection();
                        return(rq);
                    });
                    if (!rabbitQueue.EnsureConnection())
                    {
                        continue;
                    }
                    rabbitQueue.EnsureExchange();
                    var props = rabbitQueue.Channel.CreateBasicProperties();
                    props.CorrelationId = crId;
                    props.Priority      = _priority;
                    props.Expiration    = _expiration;
                    props.AppId         = Core.ApplicationName;
                    props.ContentType   = SenderSerializer.MimeTypes[0];
                    props.DeliveryMode  = _deliveryMode;
                    props.Type          = _label;
                    if (!string.IsNullOrEmpty(replyTo))
                    {
                        if (string.IsNullOrEmpty(queue.Name))
                        {
                            Core.Log.LibVerbose("Sending {0} bytes to the Queue '{1}' with CorrelationId={2}", message.Count, rabbitQueue.Route + "/" + replyTo, crId);
                            rabbitQueue.Channel.BasicPublish(rabbitQueue.ExchangeName ?? string.Empty, replyTo, props, (byte[])message);
                        }
                        else if (queue.Name.StartsWith(replyTo, StringComparison.Ordinal))
                        {
                            Core.Log.LibVerbose("Sending {0} bytes to the Queue '{1}' with CorrelationId={2}", message.Count, rabbitQueue.Route + "/" + queue.Name + "_" + replyTo, crId);
                            rabbitQueue.Channel.BasicPublish(rabbitQueue.ExchangeName ?? string.Empty, queue.Name + "_" + replyTo, props, (byte[])message);
                        }
                    }
                    else
                    {
                        Core.Log.LibVerbose("Sending {0} bytes to the Queue '{1}' with CorrelationId={2}", message.Count, rabbitQueue.Route + "/" + queue.Name, crId);
                        rabbitQueue.Channel.BasicPublish(rabbitQueue.ExchangeName ?? string.Empty, queue.Name, props, (byte[])message);
                    }
                }
                catch (Exception ex)
                {
                    response = false;
                    Core.Log.Write(ex);
                }
            }
            return(response ? Task.FromResult(message.Count) : TaskHelper.CompleteValueMinus1);
        }
Esempio n. 9
0
        protected override void OnInit()
        {
            OnDispose();
            _senders              = new List <RabbitMQueue>();
            _receiver             = null;
            _receiverStopBuffered = ActionDelegate.Create(RemoveReceiverConsumer).CreateBufferedAction(60000);

            if (Config != null)
            {
                if (Config.ClientQueues != null)
                {
                    _clientQueues = Config.ClientQueues.FirstOf(
                        c => c.EnvironmentName?.SplitAndTrim(",").Contains(Core.EnvironmentName) == true && c.MachineName?.SplitAndTrim(",").Contains(Core.MachineName) == true,
                        c => c.EnvironmentName?.SplitAndTrim(",").Contains(Core.EnvironmentName) == true,
                        c => c.MachineName?.SplitAndTrim(",").Contains(Core.MachineName) == true,
                        c => c.EnvironmentName.IsNullOrWhitespace());
                }
                _senderOptions          = Config.RequestOptions?.ClientSenderOptions;
                _receiverOptions        = Config.ResponseOptions?.ClientReceiverOptions;
                _receiverOptionsTimeout = TimeSpan.FromSeconds(_receiverOptions?.TimeoutInSec ?? 20);
                UseSingleResponseQueue  = _receiverOptions?.Parameters?[ParameterKeys.SingleResponseQueue].ParseTo(false) ?? false;

                if (_clientQueues != null)
                {
                    if (_clientQueues.SendQueues?.Any() == true)
                    {
                        foreach (var queue in _clientQueues.SendQueues)
                        {
                            var rabbitQueue = new RabbitMQueue(queue);
                            rabbitQueue.EnsureConnection();
                            rabbitQueue.EnsureExchange();
                            _senders.Add(rabbitQueue);
                        }
                    }

                    if (_clientQueues.RecvQueue != null)
                    {
                        _receiver = new RabbitMQueue(_clientQueues.RecvQueue);
                    }
                }
                if (_senderOptions == null)
                {
                    throw new Exception("Client Sender Options is Null.");
                }

                _priority = (byte)(_senderOptions.MessagePriority == MQMessagePriority.High ? 9 :
                                   _senderOptions.MessagePriority == MQMessagePriority.Low ? 1 : 5);
                _expiration   = (_senderOptions.MessageExpirationInSec * 1000).ToString();
                _deliveryMode = (byte)(_senderOptions.Recoverable ? 2 : 1);
            }

            Core.Status.Attach(collection =>
            {
                if (_senders != null)
                {
                    for (var i = 0; i < _senders.Count; i++)
                    {
                        if (_senders[i]?.Factory == null)
                        {
                            continue;
                        }
                        collection.Add("Sender Path: {0}".ApplyFormat(i), _senders[i].Factory.HostName);
                    }
                }
                if (_receiver?.Factory != null)
                {
                    collection.Add("Receiver Path", _receiver.Factory.HostName);
                }
            });
        }