Пример #1
0
 protected override void OnDispose()
 {
     if (_senders != null)
     {
         foreach (var sender in _senders)
         {
             sender.Close();
         }
         _senders.Clear();
         _senders = null;
     }
     if (_receiver != null)
     {
         RemoveReceiverConsumer();
         _receiver = null;
     }
     foreach (var pools in _routeConnection)
     {
         var pool        = pools.Value;
         var connections = pool.GetCurrentObjects();
         foreach (var connection in connections)
         {
             connection.Close();
         }
         pool.Clear();
     }
     _routeConnection.Clear();
 }
        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);
        }
Пример #3
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);
        }
Пример #4
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.EnsureConnectionAsync(2000, 100).WaitAndResults();
            rabbitQueue.Channel.QueueDelete(queue.Name, false, false);
            rabbitQueue.Close();
            return(true);
        }
Пример #5
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();
        }
Пример #6
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.EnsureConnectionAsync(2000, 100).WaitAndResults();
            rabbitQueue.Channel.QueuePurge(queue.Name);
            rabbitQueue.Close();
        }
 protected override void OnDispose()
 {
     if (_receiver == null)
     {
         return;
     }
     if (!string.IsNullOrEmpty(_receiverConsumerTag))
     {
         _receiver.Channel?.BasicCancel(_receiverConsumerTag);
     }
     _receiver.Close();
     _receiver = null;
 }
Пример #8
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);
            }
        }
Пример #9
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);
        }
Пример #10
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.EnsureConnectionAsync(2000, 100).WaitAndResults())
            {
                return(false);
            }
            rabbitQueue.EnsureQueue();
            rabbitQueue.EnsureExchange();
            rabbitQueue.Close();
            return(true);
        }
Пример #11
0
 protected override void OnDispose()
 {
     if (_senders != null)
     {
         foreach (var sender in _senders)
         {
             sender.Close();
         }
         _senders.Clear();
         _senders = null;
     }
     if (_receiver != null)
     {
         RemoveReceiverConsumer();
         _receiver = null;
     }
 }
Пример #12
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);
        }
Пример #13
0
        protected override async Task OnListenerTaskStartAsync(CancellationToken token)
        {
            _token    = token;
            _receiver = new RabbitMQueue(Connection);
            await _receiver.EnsureConnectionAsync(5000, int.MaxValue).ConfigureAwait(false);

            _receiver.EnsureQueue();
            _receiverConsumer           = new EventingBasicConsumer(_receiver.Channel);
            _receiverConsumer.Received += MessageReceivedHandler;
            _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);
        }
Пример #14
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);
        }
Пример #15
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(true) ?? true;

                if (_clientQueues != null)
                {
                    if (_clientQueues.SendQueues?.Any() == true)
                    {
                        foreach (var queue in _clientQueues.SendQueues)
                        {
                            var rabbitQueue = new RabbitMQueue(queue);
                            rabbitQueue.EnsureConnectionAsync(2000, int.MaxValue).WaitAndResults();
                            rabbitQueue.EnsureExchange();
                            _senders.Add(rabbitQueue);
                        }
                    }

                    if (_clientQueues.RecvQueue != null && !SendOnly)
                    {
                        _receiver = new RabbitMQueue(_clientQueues.RecvQueue);
                    }
                }
                if (_senderOptions is 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);

                CreateReceiverConsumerAsync().WaitAsync();
            }

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