示例#1
0
        protected override async Task <ResponseMessage> OnReceiveAsync(Guid correlationId, CancellationToken cancellationToken)
        {
            if (_receiverConnection is null && UseSingleResponseQueue)
            {
                throw new NullReferenceException("There is not receiver queue.");
            }

            var sw      = Stopwatch.StartNew();
            var message = ReceivedMessages.GetOrAdd(correlationId, cId => Message.Rent());

            if (!await message.WaitHandler.WaitAsync(_receiverOptionsTimeout, cancellationToken).ConfigureAwait(false))
            {
                throw new MessageQueueTimeoutException(_receiverOptionsTimeout, correlationId.ToString());
            }

            if (message.Body == MultiArray <byte> .Empty)
            {
                throw new MessageQueueBodyNullException("The Message can't be retrieved, null body on CorrelationId = " + correlationId);
            }

            Counters.IncrementTotalBytesReceived(message.Body.Count);
            Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}' with CorrelationId={2} at {3}ms", message.Body.Count, _clientQueues.RecvQueue.Name, correlationId, sw.Elapsed.TotalMilliseconds);
            var rs = ReceiverSerializer.Deserialize <ResponseMessage>(message.Body);

            ReceivedMessages.TryRemove(correlationId, out _);
            Message.Free(message);
            return(rs);
        }
示例#2
0
        private async Task ProcessingTaskAsync(byte[] data)
        {
            var oldContext = Core.ContextGroupName;

            try
            {
                (var body, var correlationId) = NATSQueueClient.GetFromMessageBody(data);

                Counters.IncrementTotalReceivingBytes(body.Count);
                Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}/{2}'", body.Count, Connection.Route, Connection.Name);
                var messageBody = ReceiverSerializer.Deserialize(body, _messageType);
                switch (messageBody)
                {
                case RequestMessage request when request.Header != null:
                    if (!string.IsNullOrEmpty(request.Header.ContextGroupName))
                    {
                        Core.ContextGroupName = request.Header.ContextGroupName;
                    }
                    request.Header.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(request.Header.TotalTime);
                    if (request.Header.ClientName != Config.Name)
                    {
                        Core.Log.Warning("The Message Client Name '{0}' is different from the Server Name '{1}'", request.Header.ClientName, Config.Name);
                    }
                    var evArgs = new RequestReceivedEventArgs(_name, Connection, request, body.Count, SenderSerializer, Config.RequestOptions.ServerReceiverOptions.CancellationBeforeClientResponseTimeoutInSec);
                    if (request.Header.ResponseQueue != null)
                    {
                        evArgs.ResponseQueues.Add(request.Header.ResponseQueue);
                    }
                    await OnRequestReceivedAsync(evArgs).ConfigureAwait(false);

                    break;

                case ResponseMessage response when response.Header != null:
                    if (!string.IsNullOrEmpty(response.Header.Request.Header.ContextGroupName))
                    {
                        Core.ContextGroupName = response.Header.Request.Header.ContextGroupName;
                    }
                    response.Header.Response.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(response.Header.Response.TotalTime);
                    var evArgs2 = new ResponseReceivedEventArgs(_name, response, body.Count);
                    await OnResponseReceivedAsync(evArgs2).ConfigureAwait(false);

                    break;
                }
                Counters.IncrementTotalMessagesProccesed();
            }
            catch (Exception ex)
            {
                Counters.IncrementTotalExceptions();
                Core.Log.Write(ex);
                Interlocked.Exchange(ref _exceptionSleep, 1);
            }
            finally
            {
                Core.ContextGroupName = oldContext;
            }
        }
示例#3
0
        public async Task <T> ReceiveAsync <T>(Guid correlationId, CancellationToken cancellationToken)
        {
            var msg = await ReceiveBytesAsync(correlationId, cancellationToken).ConfigureAwait(false);

            if (msg == null)
            {
                return(default(T));
            }
            if (typeof(T) == typeof(byte[]))
            {
                return((T)(object)msg);
            }
            return(ReceiverSerializer.Deserialize <T>(msg));
        }
示例#4
0
        private async Task ProcessingTaskAsync(NSQMessage message)
        {
            if (message.Body == null)
            {
                return;
            }
            try
            {
                Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}/{2}'", message.Body.Count, Connection.Route, Connection.Name);
                var messageBody = ReceiverSerializer.Deserialize(message.Body, _messageType);
                switch (messageBody)
                {
                case RequestMessage request when request.Header != null:
                    request.Header.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(request.Header.TotalTime);
                    if (request.Header.ClientName != Config.Name)
                    {
                        Core.Log.Warning("The Message Client Name '{0}' is different from the Server Name '{1}'", request.Header.ClientName, Config.Name);
                    }
                    var evArgs = new RequestReceivedEventArgs(_name, Connection, request, message.Body.Count);
                    if (request.Header.ResponseQueue != null)
                    {
                        evArgs.ResponseQueues.Add(request.Header.ResponseQueue);
                    }
                    await OnRequestReceivedAsync(evArgs).ConfigureAwait(false);

                    break;

                case ResponseMessage response when response.Header != null:
                    response.Header.Response.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(response.Header.Response.TotalTime);
                    var evArgs2 = new ResponseReceivedEventArgs(_name, response, message.Body.Count);
                    await OnResponseReceivedAsync(evArgs2).ConfigureAwait(false);

                    break;
                }
                Counters.IncrementTotalMessagesProccesed();
            }
            catch (Exception ex)
            {
                Counters.IncrementTotalExceptions();
                Core.Log.Write(ex);
                lock (_lock)
                    _exceptionSleep = true;
            }
        }
示例#5
0
        protected override async Task <ResponseMessage> OnReceiveAsync(Guid correlationId, CancellationToken cancellationToken)
        {
            if (_receiver is null)
            {
                throw new NullReferenceException("There is not receiver queue.");
            }

            var sw      = Stopwatch.StartNew();
            var message = ReceivedMessages.GetOrAdd(correlationId, _ => RabbitResponseMessage.Rent());

            await CreateReceiverConsumerAsync().ConfigureAwait(false);

            Interlocked.Increment(ref _receiverThreads);

            if (!await message.WaitHandler.WaitAsync(_receiverOptionsTimeout, cancellationToken).ConfigureAwait(false))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }
                throw new MessageQueueTimeoutException(_receiverOptionsTimeout, correlationId.ToString());
            }

            if (message.Body is null)
            {
                throw new MessageQueueBodyNullException("The Message can't be retrieved, null body on CorrelationId = " + correlationId);
            }

            Counters.IncrementTotalBytesReceived(message.Body.Length);
            Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}' with CorrelationId={2} at {3}ms", message.Body.Length, _clientQueues.RecvQueue.Name, correlationId, sw.Elapsed.TotalMilliseconds);
            var response = ReceiverSerializer.Deserialize <ResponseMessage>(message.Body);

            if (Interlocked.Decrement(ref _receiverThreads) <= 0)
            {
                _receiverStopBuffered();
            }

            RabbitResponseMessage.Free(message);
            return(response);
        }
示例#6
0
        private async Task ProcessingTaskAsync(RabbitMessage message)
        {
            if (message.Body is null)
            {
                RabbitMessage.Return(message);
                return;
            }
            var oldContext = Core.ContextGroupName;

            try
            {
                Counters.IncrementTotalReceivingBytes(message.Body.Length);
                Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}/{2}'", message.Body.Length, _receiver.Route, _receiver.Name);
                var messageBody = ReceiverSerializer.Deserialize(message.Body, _messageType);
                switch (messageBody)
                {
                case RequestMessage request when request.Header != null:
                    if (!string.IsNullOrEmpty(request.Header.ContextGroupName))
                    {
                        Core.ContextGroupName = request.Header.ContextGroupName;
                    }
                    request.Header.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(request.Header.TotalTime);
                    if (request.Header.ClientName != Config.Name)
                    {
                        Core.Log.Warning("The Message Client Name '{0}' is different from the Server Name '{1}'", request.Header.ClientName, Config.Name);
                    }
                    var evArgs = new RequestReceivedEventArgs(_name, _receiver, request, message.Body.Length, SenderSerializer, Config.RequestOptions.ServerReceiverOptions.CancellationBeforeClientResponseTimeoutInSec);
                    evArgs.Metadata["ReplyTo"]   = message.Properties.ReplyTo;
                    evArgs.Metadata["MessageId"] = message.Properties.MessageId;
                    if (request.Header.ResponseQueue != null)
                    {
                        evArgs.ResponseQueues.Add(request.Header.ResponseQueue);
                    }
                    await OnRequestReceivedAsync(evArgs).ConfigureAwait(false);

                    break;

                case ResponseMessage response when response.Header != null:
                    if (!string.IsNullOrEmpty(response.Header.Request.Header.ContextGroupName))
                    {
                        Core.ContextGroupName = response.Header.Request.Header.ContextGroupName;
                    }
                    response.Header.Response.ApplicationReceivedTime = Core.Now;
                    Counters.IncrementReceivingTime(response.Header.Response.TotalTime);
                    var evArgs2 = new ResponseReceivedEventArgs(_name, response, message.Body.Length);
                    evArgs2.Metadata["ReplyTo"]   = message.Properties.ReplyTo;
                    evArgs2.Metadata["MessageId"] = message.Properties.MessageId;
                    await OnResponseReceivedAsync(evArgs2).ConfigureAwait(false);

                    break;
                }
                Counters.IncrementTotalMessagesProccesed();
            }
            catch (Exception ex)
            {
                Counters.IncrementTotalExceptions();
                Core.Log.Write(ex);
                Interlocked.Exchange(ref _exceptionSleep, 1);
            }
            finally
            {
                Core.ContextGroupName = oldContext;
                RabbitMessage.Return(message);
            }
        }
示例#7
0
        protected override async Task <ResponseMessage> OnReceiveAsync(Guid correlationId, CancellationToken cancellationToken)
        {
            if (_receiver == null)
            {
                throw new NullReferenceException("There is not receiver queue.");
            }

            var sw      = Stopwatch.StartNew();
            var message = new RabbitResponseMessage();

            ReceivedMessages.TryAdd(correlationId, message);

            Interlocked.Increment(ref _receiverThreads);
            var strCorrelationId = correlationId.ToString();

            if (UseSingleResponseQueue)
            {
                CreateReceiverConsumer();
            }
            else
            {
                var recName   = _receiver.Name + "_" + strCorrelationId;
                var pool      = _routeConnection.GetOrAdd(_receiver.Route, r => new ObjectPool <RabbitMQueue>(p => new RabbitMQueue(_receiver)));
                var cReceiver = pool.New();
                cReceiver.EnsureConnection();
                cReceiver.Channel.QueueDeclare(recName, false, false, true, null);
                var tmpConsumer = new EventingBasicConsumer(cReceiver.Channel);
                tmpConsumer.Received += (ch, ea) =>
                {
                    var crId = Guid.Parse(ea.BasicProperties.CorrelationId);

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

                    rMessage.CorrelationId = crId;
                    rMessage.Body          = ea.Body;
                    rMessage.Properties    = ea.BasicProperties;
                    rMessage.WaitHandler.Set();
                    cReceiver.Channel.BasicAck(ea.DeliveryTag, false);
                    if (_correlationIdConsumers.TryRemove(crId, out var consumerTag))
                    {
                        cReceiver.Channel.BasicCancel(consumerTag);
                    }
                    cReceiver.Channel.QueueDeleteNoWait(recName);
                    cReceiver.AutoClose();
                    pool.Store(cReceiver);
                };
                _correlationIdConsumers.TryAdd(correlationId, cReceiver.Channel.BasicConsume(recName, false, tmpConsumer));
            }

            if (!await message.WaitHandler.WaitAsync(_receiverOptionsTimeout, cancellationToken).ConfigureAwait(false))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }
                throw new MessageQueueTimeoutException(_receiverOptionsTimeout, strCorrelationId);
            }

            if (message.Body == null)
            {
                throw new MessageQueueNotFoundException("The Message can't be retrieved, null body on CorrelationId = " + strCorrelationId);
            }

            Core.Log.LibVerbose("Received {0} bytes from the Queue '{1}' with CorrelationId={2}", message.Body.Length, _clientQueues.RecvQueue.Name, strCorrelationId);
            var response = ReceiverSerializer.Deserialize <ResponseMessage>(message.Body);

            Core.Log.LibVerbose("Correlation Message ({0}) received at: {1}ms", strCorrelationId, sw.Elapsed.TotalMilliseconds);
            sw.Stop();

            if (Interlocked.Decrement(ref _receiverThreads) <= 0)
            {
                _receiverStopBuffered();
            }

            return(response);
        }