public void StartReceivingCommands(CommandReceivedCallback callback) { CheckDisposed(); var consumer = new EventingBasicConsumer(_channel); _channel.BasicConsume(queue: QueueName, autoAck: false, consumerTag: "", noLocal: false, exclusive: false, arguments: null, consumer: consumer); consumer.Received += (s, ea) => { var body = ea.Body; var props = ea.BasicProperties; var replyProps = _channel.CreateBasicProperties(); replyProps.CorrelationId = props.CorrelationId; _logger.LogInformation("Received command request with correlation id {0}", ea.BasicProperties.CorrelationId); var message = Encoding.UTF8.GetString(body); CommandResponseMessage response = null; try { response = callback(new CommandRequestMessage(message, props.CorrelationId)).Result; replyProps.Type = response.MessageType.ToString(); } catch (Exception e) { var realException = e.InnerException; if (realException is TargetInvocationException) { realException = realException.InnerException; } response = new CommandResponseMessage(realException.Message, realException.GetType().FullName, props.CorrelationId); replyProps.Type = realException.GetType().FullName; } finally { _channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, mandatory: false, basicProperties: replyProps, body: response?.EncodeMessage()); _channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } }; }
public async Task Handle(object s, BasicDeliverEventArgs ea, CommandReceivedCallback callback) { var body = ea.Body; var props = ea.BasicProperties; var replyProps = _channel.CreateBasicProperties(); replyProps.CorrelationId = props.CorrelationId; var message = Encoding.UTF8.GetString(body); CommandResponseMessage response = null; try { response = await callback(new CommandRequestMessage(message, props.CorrelationId)); replyProps.Type = response.MessageType.ToString(); } catch (Exception e) { var realException = e.InnerException; response = new CommandResponseMessage(realException.Message, realException.GetType().ToString(), props.CorrelationId); replyProps.Type = realException.GetType().ToString(); } finally { _channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, mandatory: false, basicProperties: replyProps, body: response?.EncodeMessage()); _channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } _log.LogInformation("Started listening for commands on queue {0} ", QueueName); }