public void Listen(CancellationToken cancellationToken) { var consumer = new EventingBasicConsumer(_channel); consumer.Received += (bc, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); _logger.LogInformation($"Processing message: '{message}'."); try { var command = EventBase.Deserialize(message); var commandHandler = _eventHandlerManager.GetHandler(command); if (commandHandler != null) { Task.Run(async() => await commandHandler.HandleAsync(command, cancellationToken), cancellationToken); } _channel.BasicAck(ea.DeliveryTag, false); } catch (JsonException) { _logger.LogError($"JSON Parse Error: '{message}'."); _channel.BasicNack(ea.DeliveryTag, false, false); } catch (AlreadyClosedException) { _logger.LogInformation("RabbitMQ is closed!"); } catch (Exception e) { _logger.LogError(e, $"An error has occurred: {e.Message}"); } }; _channel.BasicConsume(queue: _rabbitMqConfiguration.ConsumeQueueName, autoAck: false, consumer: consumer); }
/// <summary> /// Called when byte array is identified as an event. Deserializes and dispatches it. /// </summary> /// <param name="stream">Data stream.</param> /// <param name="flags">Stream flags (reliable or unreliable event?).</param> /// <returns><c>true</c> if stream was handled correctly, <c>false</c> otherwise.</returns> bool HandleEvent(ByteStreamReader stream, byte flags) { if (HasFlag(flags, ( byte )MsgFlags.UnreliableEvent)) { byte eventType = stream.ReadByte(); EventBase evnt = m_events.CreateEvent(eventType); //Network.Log("Event type: " + evnt.GetEventType()); evnt.Deserialize(stream); m_dispatcher.PushEvent(evnt); return(true); } else if (HasFlag(flags, ( byte )MsgFlags.ReliableEvent)) { byte eventType = stream.ReadByte(); EventBase evnt = m_events.CreateEvent(eventType); evnt.Deserialize(stream); m_dispatcher.PushEvent(evnt); return(true); } return(false); }