コード例 #1
0
ファイル: Consumer.cs プロジェクト: SerhiiRbk/ActiveMQ
        static void TheCallback(IReceiverLink link, Message message)
        {
            //Interlocked.Increment(ref ReceivedMessages);
            //Console.WriteLine((Point)message.Body);

            link.Accept(message);
        }
コード例 #2
0
        static void TheCallback(IReceiverLink link, Message message)
        {
            Interlocked.Increment(ref ReceivedMessages);
            try
            {
                var settings = new JsonSerializerSettings();
                settings.TypeNameHandling         = TypeNameHandling.Auto;
                settings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
                settings.DateParseHandling        = DateParseHandling.None;
                var point = JsonConvert.DeserializeObject <Point>(message.Body.ToString(), settings);
                if (point.X > 99900)
                {
                    sw1.Stop();
                    Console.WriteLine(sw1.Elapsed);
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            }

            Console.WriteLine(message.Body.ToString());

            link.Accept(message);
        }
コード例 #3
0
        private void OnMessageReceived(IReceiverLink receiver, Message message)
        {
            List <CFXEnvelope> envelopes = null;

            try
            {
                envelopes = AmqpUtilities.EnvelopesFromMessage(message);
            }
            catch (Exception ex)
            {
                envelopes = null;
                AppLog.Error(ex);
            }

            if (envelopes != null && OnCFXMessageReceived != null)
            {
                try
                {
                    receiver.Accept(message);
                    envelopes.ForEach(env => OnCFXMessageReceived(new AmqpChannelAddress()
                    {
                        Uri = NetworkUri, Address = receiver.Name
                    }, env));
                }
                catch (Exception ex)
                {
                    AppLog.Error(ex);
                }
            }
        }
コード例 #4
0
        protected virtual async void OnMessageCallback(IReceiverLink receiver, Message message)
        {
            try {
                // Get the body
                var rawBody     = message.Body as string;
                var typeString  = message.ApplicationProperties[MESSAGE_TYPE_KEY] as string;
                var dataType    = EventTypeLookup[typeString];
                var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType);

                var data    = JsonConvert.DeserializeObject(rawBody, dataType);
                var handler = Provider.GetService(handlerType);

                if (handler != null)
                {
                    //TODO: Update the way "Handle" is retrieved in a type safe way.
                    var method = handlerType.GetTypeInfo().GetDeclaredMethod("Handle");
                    await(Task) method.Invoke(handler, new object[] { data });

                    receiver.Accept(message);
                }
                else
                {
                    var desc = $"Handler not found for {typeString}";
                    Logger.LogWarning(desc);
                    receiver.Reject(message);
                }
            } catch (Exception ex) {
                Logger.LogError(101, ex, ex.Message);
                receiver.Reject(message);
            }
        }
コード例 #5
0
ファイル: LinkTests.cs プロジェクト: shrirsm/amqpnetlite
        public void TestMethod_InterfaceSendReceive()
        {
            string      testName   = "InterfaceSendReceive";
            const int   nMsgs      = 200;
            IConnection connection = new Connection(testTarget.Address);
            ISession    session    = connection.CreateSession();
            ISenderLink sender     = session.CreateSender("sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("msg" + i);
                message.Properties = new Properties()
                {
                    GroupId = "abcdefg"
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message, null, null);
            }

            IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            connection.Close();
        }
コード例 #6
0
        private static void OnMessageReceived(IReceiverLink receiver, Message message)
        {
            // Ack that we got the message.
            receiver.Accept(message);

            // Ignore messages that don't have a body
            if (message.Body == null)
            {
                return;
            }

            // Ignore messages that are not a serialized FiniteDto
            var dtoName = JsonDtoSerializer.GetDtoName(message.Body.ToString());

            if (string.IsNullOrWhiteSpace(dtoName))
            {
                return;
            }

            // TODO: recode this to not be a switch (instead a map)
            switch (dtoName)
            {
            case "DescriptiveTextDto":
                var dto = JsonDtoSerializer.DeserializeAs <DescriptiveTextDto>(message.Body.ToString());
                Windows.WriteMainWindowDescriptiveText($"\r\n{dto.Text}");
                break;
            }
        }
        private static void ProcessMessage(IReceiverLink receiver, Message message)
        {
            var msg = Encoding.UTF8.GetString((byte[])message.Body);

            _receivedMessages.Add(msg);
            receiver.Accept(message);
        }
コード例 #8
0
        private void OnMessage(IReceiverLink receiverLink, Message message)
        {
            try
            {
                var ret = false;

                try
                {
                    ret = _MessageReceiver(message);
                }
                catch (Exception e)
                {
                    Logger.Error("Exception in onMessageReceived!", e);
                }

                if (ret)
                {
                    Logger.Debug("Message has been accepted.");
                    receiverLink?.Accept(message);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
コード例 #9
0
        private void OnMessageReceived(IReceiverLink receiver, Message message)
        {
            List <CFXEnvelope> envelopes = null;

            try
            {
                envelopes = AmqpUtilities.EnvelopesFromMessage(message);
            }
            catch (Exception ex)
            {
                envelopes = null;
                AppLog.Error(ex);
            }

            if (envelopes == null || (envelopes != null && envelopes.Count < 1))
            {
                try
                {
                    receiver.Accept(message);
                    AppLog.Error(string.Format("Malformed Message Received:  {0}", AmqpUtilities.MessagePreview(message)));
                    Endpoint?.Channel_OnMalformedMessageReceived(new AmqpChannelAddress()
                    {
                        Uri = NetworkUri, Address = receiver.Name
                    }, AmqpUtilities.StringFromEnvelopes(message));
                }
                catch (Exception ex)
                {
                    AppLog.Error(ex);
                }
            }
            else if (envelopes != null && OnCFXMessageReceived != null)
            {
                try
                {
                    receiver.Accept(message);
                    envelopes.ForEach(env => OnCFXMessageReceived(new AmqpChannelAddress()
                    {
                        Uri = NetworkUri, Address = receiver.Name
                    }, env));
                }
                catch (Exception ex)
                {
                    AppLog.Error(ex);
                }
            }
        }
コード例 #10
0
        // Método que será chamado toda vez que uma mensagem for recebida.
        private static void OnMessageCallback(IReceiverLink receiver, Message message)
        {
            try
            {
                /*
                 * var serializer = new AmqpSerializer(new ContractResolver()
                 * {
                 *  PrefixList = new[] { "Receiver" }
                 * });
                 *
                 * Cliente cliente = message.GetBody<Cliente>(serializer);
                 * Console.WriteLine("Received {0}", cliente);
                 * receiver.Accept(message);
                 */

                // Lendo a propriedade customizada
                var messageType = message.ApplicationProperties["Message.Type.FullName"];

                // Variável para salvar o corpo da mensagem
                string body = string.Empty;
                // Pega o corpo
                var rawBody = message.Body;

                // Se o corpo é byte [] assume que foi enviado como uma BrokeredMessage
                                  // desserialize-o usando um XmlDictionaryReader
                if (rawBody is byte[])
                {
                    using (var reader = XmlDictionaryReader.CreateBinaryReader(
                               new MemoryStream(rawBody as byte[]),
                               null,
                               XmlDictionaryReaderQuotas.Max))
                    {
                        var doc = new XmlDocument();
                        doc.Load(reader);
                        body = doc.InnerText;
                    }
                }
                else   // Se o corpo for uma string
                {
                    body = rawBody.ToString();
                }

                // Escrevendo o corpo no console
                Console.WriteLine(body);

                // Aceitando a mensagem
                receiver.Accept(message);
            }
            catch (Exception ex)
            {
                receiver.Reject(message);
                Console.WriteLine(ex);
            }
        }
コード例 #11
0
        public void OnMessage(IReceiverLink link, Message message)
        {
            ConnectionManager.WriteLine($"Called, and using the message: {message.Body}");

            ConnectionManager.WriteLine($"Accepting message number ..please wait");

            var content = message.Body;

            var bytes = (byte[])content;

            File.WriteAllBytes($@"C:\Temp\ELNOutput\{message.ApplicationProperties["CamelFileName"]}", bytes);
            link.Accept(message);
        }
コード例 #12
0
 private void OnMessageCallback(IReceiverLink receiver, Message message)
 {
     try
     {
         //var messageType = message.ApplicationProperties["Message.Type.FullName"];
         this.cliente = message.GetBody <Cliente>(serializer);
         Console.WriteLine("Received {0}", this.cliente);
         receiver.Accept(message);
     }
     catch (Exception ex)
     {
         receiver.Reject(message);
         Console.WriteLine(ex);
     }
 }
コード例 #13
0
        static private void OnMessage(IReceiverLink receiveLink, Message message)
        {
            Data data = (Data)message.BodySection;

            Console.WriteLine(UTF8Encoding.UTF8.GetString(data.Binary));
            if (message.ApplicationProperties != null)
            {
                foreach (var property in message.ApplicationProperties.Map)
                {
                    Console.WriteLine($" Key:{property.Key} Value:{property.Value}");
                }
            }

            receiveLink.Accept(message);
        }
コード例 #14
0
        public void EurexMessageCallback(IReceiverLink receiver, Message message)
        {
            Log.DebugFormat("EurexMessageCallback");

            if (message == null)
            {
                Log.WarnFormat("receiver.Receive(600000) is timeout.");
                return;
            }

            Amqp.Framing.Data payload     = (Amqp.Framing.Data)message.BodySection;
            String            payloadText = Encoding.UTF8.GetString(payload.Binary);

            Log.DebugFormat("Received message: {0}", payloadText);
            receiver.Accept(message);
        }
コード例 #15
0
 private void processResponse(IReceiverLink receiver, Message message)
 {
     receiver.Accept(message);
     if (!this._pendingRequests.TryRemove(message.Properties.CorrelationId, out var tcs))
     {
         Console.WriteLine($"No pending response for {message.Properties.CorrelationId}");
     }
     if (!this._isTimedout)
     {
         var response = message.GetBody <AmqpRpcResponse>();
         if (tcs != null)
         {
             tcs.SetResult(response);
         }
     }
 }
コード例 #16
0
        /// <summary>
        /// Method that will be called every time a message is received.
        /// </summary>
        static void OnMessageCallback(IReceiverLink receiver, Amqp.Message message)
        {
            try
            {
                // You can read the custom property
                var messageType = message.ApplicationProperties["Message.Type.FullName"];

                // Variable to save the body of the message.
                string body = string.Empty;

                // Get the body
                var rawBody = message.Body;

                // If the body is byte[] assume it was sent as a BrokeredMessage
                // and deserialize it using a XmlDictionaryReader
                if (rawBody is byte[])
                {
                    using (var reader = XmlDictionaryReader.CreateBinaryReader(
                               new MemoryStream(rawBody as byte[]),
                               null,
                               XmlDictionaryReaderQuotas.Max))
                    {
                        var doc = new XmlDocument();
                        doc.Load(reader);
                        body = doc.InnerText;
                    }
                }
                else // Asume the body is a string
                {
                    body = rawBody.ToString();
                }

                // Write the body to the Console.
                Console.WriteLine(body);

                // Accept the messsage.
                receiver.Accept(message);
            }
            catch (Exception ex)
            {
                receiver.Reject(message);
                Console.WriteLine(ex);
            }
        }
コード例 #17
0
        public void TestMethod_InterfaceSendReceiveOnAttach()
        {
            string    testName  = "InterfaceSendReceiveOnAttach";
            const int nMsgs     = 200;
            int       nAttaches = 0;

            OnAttached onAttached = (link, attach) => {
                nAttaches++;
            };

            IConnection connection = new Connection(testTarget.Address);
            ISession    session    = connection.CreateSession();
            ISenderLink sender     = session.CreateSender("sender-" + testName, new Target()
            {
                Address = testTarget.Path
            }, onAttached);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("msg" + i);
                message.Properties = new Properties()
                {
                    GroupId = "abcdefg"
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message, null, null);
            }

            IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, new Source()
            {
                Address = testTarget.Path
            }, onAttached);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            Assert.AreEqual(2, nAttaches);
            connection.Close();
        }
コード例 #18
0
        private void InvokeHandler(
            IReceiverLink receiverLink,
            Message amqpMessage,
            IMessage message,
            HostItemSubscriber subscriber)
        {
            try
            {
                DispatchModule.InvokeDispatcherInNewLifetimeScopeAsync(
                    subscriber.DispatchInfo,
                    message).GetAwaiter().GetResult();

                receiverLink.Accept(amqpMessage);
            }
            catch (Exception ex)
            {
                LogMessageReceiveEx(ex, message, subscriber.DispatchInfo);
                receiverLink.Reject(amqpMessage);
            }
        }
コード例 #19
0
ファイル: TaskTests.cs プロジェクト: szehetner/amqpnetlite
        public async Task InterfaceSendReceiveAsync()
        {
            string testName = "BasicSendReceiveAsync";
            int    nMsgs    = 100;

            IConnectionFactory factory    = new ConnectionFactory();
            IConnection        connection = await factory.CreateAsync(this.testTarget.Address);

            ISession    session = connection.CreateSession();
            ISenderLink sender  = session.CreateSender("sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message();
                message.Properties = new Properties()
                {
                    MessageId = "msg" + i, GroupId = testName
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                await sender.SendAsync(message);
            }

            IReceiverLink receiver = session.CreateReceiver("receiver-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = await receiver.ReceiveAsync(Timeout.InfiniteTimeSpan);

                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
コード例 #20
0
        public void OnMessage(IReceiverLink link, Message message)
        {
            WriteLine($"Received a message with the content: {message.Body}");
            //if (1 == 1) throw new Exception("Something wrong");
            //WriteLine("Testing sleep " + (++x));
            //Thread.Sleep(100 * 1000);

            WriteLine($"Accepted message number {_x++}");
            link.Accept(message);
            //Console.WriteLine($"Received message {message.Body}");
            //Debug.WriteLine($"Received message {message.Body}");

            //WriteLine($"started a long running job at {DateTime.Now}");
            //for (int i = 0; i < 150; i++)
            //{
            //    Console.Write(i + " ");
            //    //user = container.UserService.GetUserProfile();

            //    var fileContent = File.ReadAllText(@"C:\temp\test.txt");
            //}
            //WriteLine($"finished a long running job at {DateTime.Now}");
        }
コード例 #21
0
        protected virtual async void OnMessageCallback(IReceiverLink receiver, Message message)
        {
            var messageType = message.ApplicationProperties[MESSAGE_TYPE_KEY] as string;

            using (Logger.BeginScope(new Dictionary <string, object> {
                ["CorrelationId"] = message.Properties.CorrelationId,
                ["MessageId"] = message.Properties.MessageId,
                ["MessageType"] = messageType
            })) {
                Logger.LogInformation($"Received message {message.Properties.MessageId}");
                try {
                    string rawBody = null;
                    // Get the body
                    if (message.Body is string)
                    {
                        rawBody = message.Body as string;
                    }
                    else if (message.Body is byte[])
                    {
                        using (var reader = XmlDictionaryReader.CreateBinaryReader(
                                   new MemoryStream(message.Body as byte[]),
                                   null,
                                   XmlDictionaryReaderQuotas.Max)) {
                            var doc = new XmlDocument();
                            doc.Load(reader);
                            rawBody = doc.InnerText;
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Message {message.Properties.MessageId} has body with an invalid type {message.Body.GetType().ToString()}");
                    }

                    Logger.LogTrace($"Received message {message.Properties.MessageId} with body: {rawBody}");
                    Logger.LogDebug($"Event type key: {messageType}");
                    var dataType = EventTypeLookup[messageType];
                    Logger.LogDebug($"Event type: {dataType}");
                    var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType);
                    Logger.LogDebug($"Event type handler interface: {handlerType}");
                    var handler = Provider.GetService(handlerType);

                    if (handler != null)
                    {
                        Logger.LogDebug($"Event type handler: {handler.GetType()}");

                        var data = JsonConvert.DeserializeObject(rawBody, dataType);
                        Logger.LogDebug($"Successfully deserialized body to {dataType}");

                        //TODO: Update the way "Handle" is retrieved in a type safe way.
                        var eventType = typeof(DomainEventMessage <>).MakeGenericType(dataType);

                        var method1 = handlerType.GetTypeInfo().GetMethod("Handle", new Type[] { eventType });
                        var method2 = handlerType.GetTypeInfo().GetMethod("Handle", new Type[] { dataType });
                        if (method1 != null)
                        {
                            dynamic domainEvent = Activator.CreateInstance(eventType);
                            domainEvent.MessageId     = message.Properties.MessageId;
                            domainEvent.CorrelationId = message.Properties.CorrelationId;
                            domainEvent.Data          = (dynamic)data;
                            await(Task) method1.Invoke(handler, new object[] { domainEvent });
                        }
                        else
                        {
                            await(Task) method2.Invoke(handler, new object[] { data });
                        }

                        receiver.Accept(message);
                        Logger.LogInformation($"Message {message.Properties.MessageId} accepted");
                    }
                    else
                    {
                        receiver.Reject(message);
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because handler was not found for type {messageType}");
                    }
                } catch (Exception ex) {
                    receiver.Reject(message);
                    Logger.LogError(ex, $"Message {message.Properties.MessageId} rejected because of unhandled exception {ex.Message}");
                }
            }
        }
コード例 #22
0
        private async void ProcessIncomingRpcRequestAsync(IReceiverLink receiver, Message message)
        {
            //Accept the message since we would be replying using sender, hence disposition does not make sense
            await Task.Run(async() =>
            {
                receiver.Accept(message);
                //Deserialize the body
                AmqpRpcRequest _rpcRequest = message.GetBody <AmqpRpcRequest>();
                string _replyTo            = message.Properties.ReplyTo;
                string _correlationId      = message.Properties.CorrelationId;

                if (!_rpMethodTypes.Contains(_rpcRequest.Type))
                {
                    Log.Error($"Invalid request type received: {_rpcRequest.Type}");
                    await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: new AmqpRpcInvalidRpcTypeException(_rpcRequest.Type));
                    return;
                }
                if (string.IsNullOrEmpty(_rpcRequest.Method))
                {
                    Log.Error("Missing RPC function call name: {@_rpcRequest}", _rpcRequest);
                    await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: new AmqpRpcMissingFunctionNameException(JsonConvert.SerializeObject(_rpcRequest)));
                    return;
                }
                if (!this._serverFunctions.ContainsKey(_rpcRequest.Method))
                {
                    Log.Error($"Unknown RPC method request received: {_rpcRequest.Method}");
                    await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: new AmqpRpcUnknownFunctionException($"{_rpcRequest.Method} is not bound to remote server"));
                    return;
                }
                var _requestObjectType = this._serverFunctions.SingleOrDefault(x => x.Key.Equals(_rpcRequest.Method));
                if (_requestObjectType.Value == null)
                {
                    Log.Error($"Unknown RPC method request received: {_rpcRequest.Method}");
                    await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: new AmqpRpcUnknownFunctionException($"{_rpcRequest.Method} is not bound to remote server"));
                    return;
                }

                var _methodParameter = this._utility.PeeloutAmqpWrapper(deserializationType: _requestObjectType.Value.RequestParameterType, parameters: _rpcRequest.Parameters);
                var _classInstance   = Activator.CreateInstance(_requestObjectType.Value.FunctionWrapperType);
                MethodInfo _method   = _requestObjectType.Value.FunctionWrapperType.GetMethod(_requestObjectType.Key);

                var _asyncAttribute = _method.GetCustomAttribute <AsyncStateMachineAttribute>();
                var _isAsync        = (_asyncAttribute != null) || (_method.ReturnType.BaseType.Equals(typeof(Task)));

                try
                {
                    if (!(_methodParameter is null) && _method.GetParameters().Length > 0)
                    {
                        //TODO: check for missing properties from rpc calls
                        //await this.SendResponse(replyTo: _replyTo, correlationId: _correlationId, _rpcRequest.type, null, new AmqpRpcUnknowParameterException($"{_rpcRequest.method} invokation failed, mismatch in parameter"));
                        object _rtnVal = null;
                        try
                        {
                            if (_isAsync)
                            {
                                _rtnVal = await(dynamic) _method.Invoke(_classInstance, new[] { _methodParameter });
                            }
                            else
                            {
                                _rtnVal = _method.Invoke(_classInstance, new[] { _methodParameter });
                            }
                            await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: _rtnVal, ex: null);
                        }
                        catch (Exception ex)
                        {
                            await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: ex);
                            return;
                        }
                    }
                    else if (_methodParameter is null && _method.GetParameters().Length.Equals(0))
                    {
                        object _rtnVal = null;
                        try
                        {
                            if (_isAsync)
                            {
                                _rtnVal = await(dynamic) _method.Invoke(_classInstance, null);
                            }
                            else
                            {
                                _rtnVal = _method.Invoke(_classInstance, null);
                            }
                            await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: _rtnVal, ex: null);
                        }
                        catch (Exception ex)
                        {
                            await this.SendResponseAsync(replyTo: _replyTo, correlationId: _correlationId, requestType: _rpcRequest.Type, response: null, ex: ex);
                            return;
                        }
                    }
コード例 #23
0
 public void Accept()
 {
     link.Accept(message);
 }
コード例 #24
0
        protected async Task OnMessageCallbackAsync(IReceiverLink receiver, Message message)
        {
            var messageTypeName = message.ApplicationProperties[Constants.MESSAGE_TYPE_KEY] as string;
            var properties      = new Dictionary <string, object> {
                ["CorrelationId"] = message.Properties.CorrelationId,
                ["MessageId"]     = message.Properties.MessageId,
                ["MessageType"]   = messageTypeName
            };

            // if message has correlationId, set it so that handling can be found by initial correlation
            if (!string.IsNullOrWhiteSpace(message.Properties.CorrelationId))
            {
                CorrelationContext.SetCorrelationId(message.Properties.CorrelationId);
            }

            var timer = new Stopwatch();

            timer.Start();

            using (Logger.BeginScope(properties)) {
                Logger.LogInformation($"Received message {message.Properties.MessageId}");

                try {
                    string body = DomainEventMessage.GetBody(message);
                    Logger.LogTrace("Received message {MessageId} with body: {MessageBody}", message.Properties.MessageId, body);

                    Logger.LogDebug($"Event type key: {messageTypeName}");
                    if (!EventTypeLookup.ContainsKey(messageTypeName))
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because message type was not registered for type {messageTypeName}");
                        receiver.Reject(message);
                        return;
                    }

                    var dataType = EventTypeLookup[messageTypeName];
                    Logger.LogDebug($"Event type: {dataType}");
                    var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType);
                    Logger.LogDebug($"Event type handler interface: {handlerType}");
                    var handler = Provider.GetService(handlerType);
                    if (handler == null)
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because handler was not found for type {messageTypeName}");
                        receiver.Reject(message);
                        return;
                    }
                    Logger.LogDebug($"Event type handler: {handler.GetType()}");

                    dynamic domainEvent;
                    try {
                        domainEvent = DomainEventMessage.CreateGenericInstance(dataType, message);
                        Logger.LogDebug($"Successfully deserialized body to {dataType}");
                    } catch (Exception ex) {
                        Logger.LogError(ex, ex.Message);
                        receiver.Reject(message);
                        return;
                    }

                    HandlerResult result;
                    dynamic       dhandler = handler;
                    try {
                        result = await dhandler.HandleAsync(domainEvent).ConfigureAwait(false);
                    } catch (Exception ex) {
                        Logger.LogError(ex, $"Message {message.Properties.MessageId} caught unhandled exception {ex.Message}");
                        result = HandlerResult.Failed;
                    }

                    timer.Stop();
                    var duration = timer.ElapsedMilliseconds;

                    var dp = new Dictionary <string, object> {
                        ["duration"] = duration
                    };

                    using (Logger.BeginScope(dp)) {
                        Logger.LogInformation($"Handler executed for message {message.Properties.MessageId} and returned result of {result}");

                        switch (result)
                        {
                        case HandlerResult.Success:
                            receiver.Accept(message);
                            Logger.LogInformation($"Message {message.Properties.MessageId} accepted");
                            break;

                        case HandlerResult.Retry:
                            var deliveryCount = message.Header.DeliveryCount;
                            var delay         = 10 * deliveryCount;
                            var scheduleTime  = DateTime.UtcNow.AddSeconds(delay);

                            using (var ts = new TransactionScope()) {
                                var sender = new SenderLink(Link.Session, Settings.AppName + "-retry", Settings.Queue);
                                // create a new message to be queued with scheduled delivery time
                                var retry = new Message(body)
                                {
                                    Header                = message.Header,
                                    Footer                = message.Footer,
                                    Properties            = message.Properties,
                                    ApplicationProperties = message.ApplicationProperties
                                };
                                retry.ApplicationProperties[Constants.SCHEDULED_ENQUEUE_TIME_UTC] = scheduleTime;
                                sender.Send(retry);
                                receiver.Accept(message);
                            }
                            Logger.LogInformation($"Message {message.Properties.MessageId} requeued with delay of {delay} seconds for {scheduleTime}");
                            break;

                        case HandlerResult.Failed:
                            receiver.Reject(message);
                            break;

                        case HandlerResult.Release:
                            receiver.Release(message);
                            break;

                        default:
                            throw new NotImplementedException($"Unknown HandlerResult value of {result}");
                        }
                    }
                } catch (Exception ex) {
                    timer.Stop();
                    var duration = timer.ElapsedMilliseconds;

                    var dp = new Dictionary <string, object> {
                        ["duration"] = duration
                    };

                    using (Logger.BeginScope(dp)) {
                        Logger.LogError(ex, $"Message {message.Properties.MessageId} rejected because of unhandled exception {ex.Message}");
                        receiver.Reject(message);
                    }
                }
            }
        }
コード例 #25
0
 void OnMessage(IReceiverLink link, Message message)
 {
     link.Accept(message);
     this.Success(1);
 }
コード例 #26
0
        protected virtual async void OnMessageCallback(IReceiverLink receiver, Message message)
        {
            var messageType = message.ApplicationProperties[MESSAGE_TYPE_KEY] as string;

            using (Logger.BeginScope(new Dictionary <string, object> {
                ["CorrelationId"] = message.Properties.CorrelationId,
                ["MessageId"] = message.Properties.MessageId,
                ["MessageType"] = messageType
            })) {
                Logger.LogInformation($"Received message {message.Properties.MessageId}");
                try {
                    string rawBody = null;
                    // Get the body
                    if (message.Body is string)
                    {
                        rawBody = message.Body as string;
                    }
                    else if (message.Body is byte[])
                    {
                        using (var reader = XmlDictionaryReader.CreateBinaryReader(
                                   new MemoryStream(message.Body as byte[]),
                                   null,
                                   XmlDictionaryReaderQuotas.Max)) {
                            var doc = new XmlDocument();
                            doc.Load(reader);
                            rawBody = doc.InnerText;
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Message {message.Properties.MessageId} has body with an invalid type {message.Body.GetType()}");
                    }

                    Logger.LogTrace($"Received message {message.Properties.MessageId} with body: {rawBody}");
                    Logger.LogDebug($"Event type key: {messageType}");

                    if (!EventTypeLookup.ContainsKey(messageType))
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because message type was not registered for type {messageType}");
                        receiver.Reject(message);
                    }


                    var dataType = EventTypeLookup[messageType];
                    Logger.LogDebug($"Event type: {dataType}");
                    var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType);
                    Logger.LogDebug($"Event type handler interface: {handlerType}");
                    var handler = Provider.GetService(handlerType);

                    if (handler != null)
                    {
                        Logger.LogDebug($"Event type handler: {handler.GetType()}");

                        List <string> errors = new List <string>();
                        var           data   = JsonConvert.DeserializeObject(rawBody, dataType,
                                                                             new JsonSerializerSettings {
                            Error = (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) => {
                                errors.Add(args.ErrorContext.Error.Message);
                                args.ErrorContext.Handled = true;
                            }
                        });
                        if (errors.Any())
                        {
                            Logger.LogError($"Message {message.Properties.MessageId} rejected because of errors deserializing messsage body: {string.Join(", ", errors)}");
                            receiver.Reject(message);
                            return;
                        }

                        Logger.LogDebug($"Successfully deserialized body to {dataType}");

                        var eventType = typeof(DomainEventMessage <>).MakeGenericType(dataType);
                        var method    = handlerType.GetTypeInfo().GetMethod("Handle", new Type[] { eventType });

                        if (method != null)
                        {
                            dynamic domainEvent = Activator.CreateInstance(eventType);
                            domainEvent.MessageId     = message.Properties.MessageId;
                            domainEvent.CorrelationId = message.Properties.CorrelationId;
                            domainEvent.Data          = (dynamic)data;
                            await(Task) method.Invoke(handler, new object[] { domainEvent });
                        }

                        Logger.LogInformation($"Message {message.Properties.MessageId} accepted");
                        receiver.Accept(message);
                    }
                    else
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because handler was not found for type {messageType}");
                        receiver.Reject(message);
                    }
                } catch (Exception ex) {
                    Logger.LogError(ex, $"Message {message.Properties.MessageId} rejected because of unhandled exception {ex.Message}");
                    receiver.Reject(message);
                }
            }
        }